2012-09-07 60 views
0

我有這樣一個句子:正則表達式替換C#

[FindThis|foo|bar] with some text between [FindThis|foo|bar]. [FindThis|foo|bar] and some more text.

我想正則表達式替換這句話讓我得到:

FindThis with some text between FindThis. FindThis and some more text.

我該如何做到這一點?真正地嘗試所有的早晨,我想出了唯一的一點是:

Regex.Replace(myString, @"\[(\w).*\]", "$1"); 

其中僅給了我:

F and some more text.

+0

@Oded:這是行不通的,因爲'。*'是貪婪的。 – kennytm

回答

3

可以更換

\[([^|]+)[^\]]+] 

$1

一點解釋:

\[  match the opening bracket 
[^|]+ match the first part up to the | 
     (a sequence of at least one non-pipe character) 
[^\]]+ match the rest in the brackets 
     (a sequence of at least one non-closing-bracket character) 
]  match the closing bracket 

由於我們存儲在第一部分中的括號內捕獲組,我們更換了整場比賽與該組的內容。

快速PowerShell的測試:

PS> $text = '[FindThis|foo|bar] with some text between [FindThis|foo|bar]. [FindThis|foo|bar] and some more text.' 
PS> $text -replace '\[([^|]+)[^\]]+]','$1' 
FindThis with some text between FindThis. FindThis and some more text. 
0

如果您有其他的替代品,沒有 「替代品」,例如[FindThat] with text in between [Find|the|other],你需要在正則表達式略有變化:

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

的解釋:

 
\[  match the opening bracket 
[^|\]]+ match the first part up to the | or ] 
     (a sequence of at least one non-pipe or closing-bracket character) 
[^\]]* match the rest in the brackets 
     (a sequence of any non-closing-bracket characters including none) 
]  match the closing bracket 

許多這樣的答案從Joey的複製的。