2012-03-06 46 views
2

输入线路是这样的(只是它的一部分)的正则表达式: 配对括号

[[Text Text Text]][[text text text]]asdasdasdasda[[asdasdasdasd]] 

我想是列出所有比赛,其中文本封闭在一对[[]]。 我确实尝试了几种模式,但是当输入行内有未封闭的[[]]时,所有模式都失败。例如:

[[text[[text text TEXT text]] 

而且,如果一个支架上的输入线中存在,如:

[[text [text] text TEXT text]] 

我使用的正则表达式为:

\[\[[^\[\[]*\]\] 

回答

2

做什么用未封闭或单支架符合您的规格。在此之前

\[\[([^\]]|\][^\]])*\]\] 

对我的作品(其中整个两个问题的字符串匹配。

+0

你需要转义char类中的文字以保证安全... – sweaver2112 2012-03-06 09:13:31

+0

@ sweaver2112你是指在各种实现中使用通用的正则表达式吗?以上是用.NET测试的。 – 2012-03-06 09:18:23

+0

会有什么地方逃跑会受伤吗?你的模式是有效的,但在正则表达式上它没有直到我逃脱]。毕竟,它是一个特殊的字符和正则表达式引擎可能不够聪明来搞清楚。 – sweaver2112 2012-03-06 09:21:44

3
\[\[(?:(?!\[\[|\]\]).)*\]\] 

比赛[[<anything>]],其中<anything>可能不包含双括号,但一切,你可能需要设置你的正则表达式引擎的DOTALL选项允许点匹配换行符。

它将

匹配
[[don't match this [[match [this] text]] don't match this]] 

说明:

\[\[  # Match [[ 
(?:  # Match... 
(?!  # (unless we're right at the start of 
    \[\[ # [[ 
|  # or 
    \]\] # ]] 
)  # ) 
.  # ...any character 
)*  # Repeat any number of times 
\]\]  # Match ]] 

警告:它会在文本[[match[this]]]匹配[[match [this]]因为正则表达式无法计数。