2011-12-14 34 views
0

我想寫一個正則表達式,將在C#中的工作,將在正則表達式匹配的文本:[文字]

[[text is here]] 

幾乎任何的線可以走其間的匹配的東西[[]]

唯一的規則是,如果[]顯示, 連續不能超過1個。

例如

[[ text ] is here ]] is a match 
[[ text [ is ]here [ ]] is a match 
[[ text ][ is [] ]] is a match 

[[ text [[ is here]] is NOT a match. 

我一直在抓我的頭幾個小時,我拿出最接近的是

@"\[\[[^\[]+(\]\])+?" 

以上將匹配

[[text is ] here]] 

but not 

[[text is [ here]] 

任何幫助/見解將不勝感激。

+1

我有我的懷疑一個正則表達式會在這裏削減芥末,但一個簡單的解析器會很容易寫。 – 2011-12-14 01:46:00

+1

我同意馬特。溝RegEx在這裏。這將是非常複雜的,每當你想改變它,你都必須重新包裹它。通過字符串的每個字符的簡單循環將更容易理解,更改,並且計算速度更快。 – jmacinnes 2011-12-14 01:50:58

回答

2
\[\[(?:[^\[\]]|\][^\]]|\[[^[])*\]\] 

擴展:

\[\[   # match the [[ 
(?:   # and then match zero or more... 
    [^\[\]]  # character which is not [ or ], or 
| \][^\]]  # a ], followed by a non-], or 
| \[[^[]  # a [, followed by a non-[ 
)* 
\]\]   # and match the ]] 

注意,這將匹配[[ text [[ is here]] is NOT a match.[[ is here]]

0

如果我正確理解你的問題,你需要把它分成兩個正則表達式,一個測試[[ ]]部分,另一個測試連續兩個「壞」情況。 「匹配」是匹配的第一個,而不是第二個。

編輯或使用KennyTM的優越的解決方案

0

您需要積極向前看,向後看。

(?<=\[\[).*?(?=\]\])