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

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

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

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

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

\[.*?\]

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

有可能做到吗?


当前回答

我想在/和#之间找到一个字符串,但#有时是可选的。下面是我使用的正则表达式:

  (?<=\/)([^#]+)(?=#*)

其他回答

去掉[]的用法:

\[.+\]

这个特别适用于javascript的正则表达式解析器/[^[\]]+(?=])/g

在控制台中运行即可

var regex = /[^[\]]+(?=])/g;
var str = "This is a test string [more or less]";
var match = regex.exec(str);
match;

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

如果需要提取不带括号的文本,可以使用bash awk

echo[你好mundo”|啊- f”[][]{打印2美元的”

结果:

你好世界

PHP:

$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);
var_dump($match[1]);