我需要从字符串中提取一组包含在两个分隔符之间的字符,而不返回分隔符本身.
一个简单的例子应该是有用的:
目标:提取方括号之间的子字符串,而不返回括号本身.
基本字符串:This is a test string [more or less]
如果我使用以下reg.恩.
\[.*?\]
比赛是[more or less]
.我只需要more or less
(没有括号).
有可能吗?
cle*_*tus 401
轻松完成:
(?<=\[)(.*?)(?=\])
Run Code Online (Sandbox Code Playgroud)
从技术上讲,这是使用前瞻和外观.请参见Lookahead和Lookbehind Zero-Width Assertions.该模式包括:
或者你可以捕捉方括号之间的内容:
\[(.*?)\]
Run Code Online (Sandbox Code Playgroud)
并返回第一个捕获的组而不是整个匹配.
Zan*_*non 48
如果您使用的是JavaScript,那么由cletus提供的第一个解决方案(?<=\[)(.*?)(?=\])
将无效,因为JavaScript不支持lookbehind运算符.
但是,第二个解决方案效果很好,但您需要获取第二个匹配的元素.
例:
var regex = /\[(.*?)\]/;
var strToMatch = "This is a test string [more or less]";
var matched = regex.exec(strToMatch);
Run Code Online (Sandbox Code Playgroud)
它将返回:
["[more or less]", "more or less"]
Run Code Online (Sandbox Code Playgroud)
所以,你需要的是第二个价值.使用:
var matched = regex.exec(strToMatch)[1];
Run Code Online (Sandbox Code Playgroud)
回来:
"more or less"
Run Code Online (Sandbox Code Playgroud)
Xet*_*ius 19
你只需要"捕获"括号之间的位.
\[(.*?)\]
Run Code Online (Sandbox Code Playgroud)
抓住你把它放在括号内.你没有说这是使用哪种语言.例如,在Perl中,您可以使用$ 1变量访问它.
my $string ='This is the match [more or less]';
$string =~ /\[(.*?)\]/;
print "match:$1\n";
Run Code Online (Sandbox Code Playgroud)
其他语言将有不同的机制.例如,C#使用Match集合类,我相信.
PHP:
$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);
var_dump($match[1]);
Run Code Online (Sandbox Code Playgroud)
小智 7
[^\[]
匹配任何不是[.
+
匹配任何不符合的1个或更多[
.创建这些匹配的组.
(?=\])
积极的向前看]
.匹配以结尾]
而不包括在结果中的组.
完成.
[^\[]+(?=\])
Run Code Online (Sandbox Code Playgroud)
证明.
类似于null提出的解决方案.但\]
不需要额外的.作为补充说明,它似乎\
不需要逃脱[
后^
.为了便于阅读,我会留下它.
在分隔符相同的情况下不起作用."more or less"
例如.
如果您使用 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' ]
Run Code Online (Sandbox Code Playgroud)
如您所见,这对于文本中的多个分隔符也很有用
这是一个带有明显分隔符(X
和Y
)的一般示例:
(?<=X)(.*?)(?=Y)
Run Code Online (Sandbox Code Playgroud)
在这里它的使用之间找到字符串X
和Y
。此处为Rubular 示例,或参见图片:
小智 5
这个专门用于 javascript 的正则表达式解析器 /[^[\]]+(?=])/g
只需在控制台中运行它
var regex = /[^[\]]+(?=])/g;
var str = "This is a test string [more or less]";
var match = regex.exec(str);
match;
Run Code Online (Sandbox Code Playgroud)