2010-08-26 22 views
0

如何從字符串中替換五位數字? 可能是Regexes中的一個解決方案,我的正則表達式技能並不是很強。如何從字符串中替換五位數字?

string ort = "42671 VÄSTRA FRÖLUNDA"; 
+0

更多細節,你想要更換哪些?用什麼? – 2010-08-26 09:15:31

+0

如果您正在尋找從字符串開頭替換數字,則這是您需要的rgex:「^ \ d +」 – 2010-08-26 09:17:26

回答

1

\d{5}將匹配字符串中任意位置的五個數字。這可以與Regex.Replace一起使用。

2
String result = Regex.Replace("input string",@"\d{5}",ReplaceFiveDigits); 

    private static string ReplaceFiveDigits(Match m) 
    { 
     return "VALUE TO REPLACE"; 
    } 
+0

您需要替換字符串(或「MatchEvaluator」委託)的第三個參數。 – Richard 2010-08-26 09:20:24

+0

謝謝,我太匆忙了! :d – astorcas 2010-08-26 09:28:34

1
var replaced = Regex.Replace(ort, @"\d{5}", "REPLACE WITH THIS"); 

將取代任何5個連續的數字。

您是否也想要刪除空間後?

var replaced = Regex.Replace(ort, @"\d{5}\s?", "REPLACE WITH THIS");