我需要从字符串中提取包含在两个分隔符之间的一组字符,而不返回分隔符本身。

一个简单的例子应该会有所帮助:

目标:提取方括号之间的子字符串,不返回方括号本身。

基本字符串:这是一个测试字符串[或多或少]

如果我使用下面的reg。前女友。

\[.*?\]

比赛[差不多]进行得很顺利。我只需要得到更多或更少(没有括号)。

有可能做到吗?


当前回答

下面是一个带有明显分隔符(X和Y)的一般示例:

(?<=X)(.*?)(?=Y)

在这里,它用于查找X和y之间的字符串。

其他回答

我在使用regex和bash脚本时遇到了同样的问题。 我使用了一个两步解决方案,使用管道并应用grep -o

 '\[(.*?)\]'  

首先,然后

'\b.*\b'

显然在其他答案上没有那么有效,但这是另一种选择。

去掉[]的用法:

\[.+\]

下面是我在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]);

最新解决方案

如果你使用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' ]

如您所见,这对于文本中的多个分隔符也很有用