我需要从字符串中提取包含在两个分隔符之间的一组字符,而不返回分隔符本身。
一个简单的例子应该会有所帮助:
目标:提取方括号之间的子字符串,不返回方括号本身。
基本字符串:这是一个测试字符串[或多或少]
如果我使用下面的reg。前女友。
\[.*?\]
比赛[差不多]进行得很顺利。我只需要得到更多或更少(没有括号)。
有可能做到吗?
我需要从字符串中提取包含在两个分隔符之间的一组字符,而不返回分隔符本身。
一个简单的例子应该会有所帮助:
目标:提取方括号之间的子字符串,不返回方括号本身。
基本字符串:这是一个测试字符串[或多或少]
如果我使用下面的reg。前女友。
\[.*?\]
比赛[差不多]进行得很顺利。我只需要得到更多或更少(没有括号)。
有可能做到吗?
当前回答
最新解决方案
如果你使用Javascript,我想出的最好的解决方案是使用match而不是exec方法。 然后,使用$1迭代匹配并删除带有第一组结果的分隔符
const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]
如您所见,这对于文本中的多个分隔符也很有用
其他回答
如果需要提取不带括号的文本,可以使用bash awk
echo[你好mundo”|啊- f”[][]{打印2美元的”
结果:
你好世界
去掉[]的用法:
\[.+\]
最新解决方案
如果你使用Javascript,我想出的最好的解决方案是使用match而不是exec方法。 然后,使用$1迭代匹配并删除带有第一组结果的分隔符
const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]
如您所见,这对于文本中的多个分隔符也很有用
下面是我在c#中没有'['和']'的原因:
var text = "This is a test string [more or less]";
// Getting only string between '[' and ']'
Regex regex = new Regex(@"\[(.+?)\]");
var matchGroups = regex.Matches(text);
for (int i = 0; i < matchGroups.Count; i++)
{
Console.WriteLine(matchGroups[i].Groups[1]);
}
输出结果为:
more or less
PHP:
$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);
var_dump($match[1]);