2015-04-30 62 views
3

我有一個字符串Test123(45)我想刪除括號內的數字。我會怎麼做呢?刪除字符串的特定部分中的數字(在括號內)

到目前爲止,我已經試過如下:

string str = "Test123(45)"; 
string result = Regex.Replace(str, "(\\d)", string.Empty); 

但是這導致的結果測試(),當它應該是Test123()

回答

1
\d+(?=[^(]*\)) 

嘗試this.Use與verbatinum模式@ .The先行將確保數量有)沒有( it.Replace之前empty string

查看演示。

https://regex101.com/r/uE3cC4/4

+0

非常感謝,這個作品!也是偉大的網站,沒有意識到這一點。 – SomeGuy08

+0

@ SomeGuy08:re​​gex101沒有處理.NET特定的正則表達式。使用http://regexstorm.net/tester或http://regexhero.net/tester/ –

+2

@ SomeGuy08 ..我會用ASh/fubo的解決方案..它是這個解決方案的簡化解決方案,也非常高性能..(需要非常少的步驟..我不認爲應該使用lookaheads,除非沒有實際的要求) –

1
string str = "Test123(45)"; 
string result = Regex.Replace(str, @"\(\d+\)", "()"); 
+0

'Regex.Replace(str,@「\(\ d + \)」,「()」)'將適用於格式爲'(DigitDigitDigit)'的字符串。 [result'()'];如果字符串的格式爲'(DigitSomethingDigit)',它不會刪除Digits。 [結果'(DigitSomethingDigit)'] – ASh

2

那朵替換所有括號,用括號填滿數字

string str = "Test123(45)"; 
string result = Regex.Replace(str, @"\(\d+\)", "()"); 
0

你也可以試試這個方法:

string str = "Test123(45)"; 
     string[] delimiters ={@"("};; 
     string[] split = str.Split(delimiters, StringSplitOptions.None); 
     var b=split[0]+"()"; 
0

刪除一個數字,在其實裏面括號但不包括圓括號並保留其中的任何其他內容,而非C#中的數字Regex.Replace意味着匹配所有括號子字符串與\([^()]+\)然後刪除MatchEvaluator內的所有數字。

這裏是一個C# sample program

var str = "Test123(45) and More (5 numbers inside parentheses 123)"; 
var result = Regex.Replace(str, @"\([^()]+\)", m => Regex.Replace(m.Value, @"\d+", string.Empty)); 
// => Test123() and More (numbers inside parentheses) 

要刪除括在()符號數字,ASh's \(\d+\) solution將工作做好:\(相匹配的文字(\d+比賽1+數字,\)相匹配的文字)

相關問題