2009-12-11 133 views
0

我一直在使用正則表達式匹配嵌入在方括號中的字符串[*]爲:正則表達式字符串用空格和特殊字符 - C#

new Regex(@"\[(?<name>\S+)\]", RegexOptions.IgnoreCase); 

我還需要搭配一些代碼看起來像: [ TestTable的:A,B,C,d]

它已得到空格,逗號,冒號

能否請您指導我如何修改我的上述正則表達式包含這樣的代碼。
P.S.其他代碼沒有空格/特殊字符,但總是用[...]括起來。

+0

它有助於如果你用適當的編程語言標記你的問題 – lorenzog 2009-12-11 11:48:06

+0

它的c#。 ................. – Robert 2009-12-11 11:49:41

回答

1
Regex myregex = new Regex(@"\[([^\]]*)]") 

將匹配所有不包括括號的字符,並括在括號中。捕獲組\1將匹配括號內的內容。

解釋(的RegexBuddy提供):

Match the character 「[」 literally «\[» 
Match the regular expression below and capture its match into backreference number 1 «([^\]]*)» 
    Match any character that is NOT a ] character «[^\]]*» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
Match the character 「]」 literally «]» 

這也會,如果你有一個以上的對你要找的字符串匹配括號的工作。它將而不是工作,如果方括號可以嵌套,例如, G。 [Blah [Blah] Blah]

0
/\[([^\]:])*(?::([^\]]*))?\]/ 

捕獲組1將包含整個標籤,如果它不具有結腸,或者如果它在冒號之前的部分。

捕獲組2將包含冒號後的部分。然後,您可以拆分','並修剪每個條目以獲取單個零件。

相關問題