5

这个问题中,提供了一个用于捕获分隔符之间的字符串的正则表达式:

测试: This is a test string [more or less]

正则表达式: (?<=\[)(.*?)(?=\])

回报: more or less

如果要捕获的字符串也包含分隔符怎么办?

测试1: This is a test string [more [or] less]

返回1: more [or] less

测试 2: This is a test string [more [or [and] or] less]

返回2: more [or [and] or] less

和多个括号?

测试 3: This is a test string [more [or [and] or] less] and [less [or [and] or] more]

返回 3: more [or [and] or] less ,less [or [and] or] more

哪个正则表达式会这样做?或者哪个小的 ruby​​/python 脚本可以做到这一点?

4

1 回答 1

7

在 JavaScript 中

var str = 'This is a test string [more [or [and] or] less]';    
str = str.match( /\[(.+)\]/ )[1];
// "more [or [and] or] less"

如果省略?.+将贪婪地匹配到最后一个]

在蟒蛇

str = "This is a test string [more [or [and] or] less]"
re.search( "(?<=\[).+(?=\])", str ).group()
// "more [or [and] or] less"

更新多个嵌套括号

在 JavaScript 中

var matches = [],
    str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]';

str.replace( /\[([^\]]*\[?[^\]]*\]?[^[]*)\]/g, function ( $0, $1 ) {
    $1 && matches.push( $1 );
});

console.log( matches );
// [ "more [or [and] or] less", "less [or [and] or] more", "more" ]

在蟒蛇

import re
str = 'This is a test string [more [or [and] or] less] and [less [or [and] or] more] and [more]'

matches = re.findall( r'\[([^\]]*\[?[^\]]*\]?[^[]*)\]', str )

print matches
# [ 'more [or [and] or] less', 'less [or [and] or] more', 'more' ]
于 2013-02-22T19:05:44.577 回答