2012-10-12 53 views
1

鑑於以下〜應變:正則表達式開始用[和結尾] - 匹配的話只

var s = "my [first] ga[m]e and [abc]de]\nThe [Game]" 

這正則表達式做我用它來搭配:

0 - [first] 
1 - [abc]de] 
2 - [Game] 

我試圖var pattern2 = new Regex(@"\W\[.*?\]\W");但它不」找不到[Game]

我也希望能夠匹配「[my] gamers\t[pro]

0 - [my] 
1 - [pro] 
+0

可能的重複:http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets進一步閱讀:http://stackoverflow.com/questions/524548/regular-expression -to-detect-sem-colon-terminated-c-for-while-loops/524624#524624 – hometoast

+0

我不認爲它是重複的。他不在尋找平衡括號('[abc] de]'不平衡),他正在尋找位於單詞邊界的括號。 – Barmar

回答

4
\[[^\[]{2,}\] 

說明:

\[   # Match a [ 
[^\[]{2,} # Match two or more non-[ characters 
\]   # Match ] 

看到它的RegExr

+0

好,但我仍然不得不考慮它,儘管解釋。 :) – Chris

+0

我不認爲這是工作。我將輸入改爲'my [first] ga [m] e和] de] \ n [Game]'並匹配'[m] e和] de]'。 – Barmar

+0

@Barmar:是的,正則表達式允許除了[[]兩個分隔括號之外的任何字符。關於什麼是什麼和什麼是不允許在一個「單詞」中的規格不是很清楚。或許'\ [\ S {2,} \]'會更好一些(只允許括號內的非空格字符) - 但OP仍然需要指定。 –

0

你需要明確匹配字符串的開頭和結尾,除了非單詞字符:

(?:^|\W)\[(.*?)\](?:$|\W) 

捕獲組將會得到括號內的字。

相關問題