tags:

views:

80

answers:

3

How to replace five digits from a string? Possibly a solution in Regexes, my regular expression skills are not so strong.

string ort = "42671 VÄSTRA FRÖLUNDA"; 
+1  A: 

\d{5} will match five digits anywhere in a string. This can be used with Regex.Replace.

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

    private static string ReplaceFiveDigits(Match m)
    {
        return "VALUE TO REPLACE";
    }
astorcas
You need a 3rd argument for the replacement string (or `MatchEvaluator` delegate).
Richard
thank you, I was too hasty! :D
astorcas
+1  A: 
var replaced = Regex.Replace(ort, @"\d{5}", "REPLACE WITH THIS");

will replace any 5 consecutive digits.

do you also want to remove the space afterwards?

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