But what about if you have to deal with patterns to replace or manipulate partial string?
Here you have to go beyond String.Replace and deal with regular expressions.
If you have't heared about Regular Expressions, I suggest to read this articles about it:
- Regular Expression article @ wikipedia (german: Regülärer Ausdruck)
- MSDN: Regex (german: Regex)
- The 30 Minute Regex Tutorial @ codeproject.com
And now, time for some excamples.
Assume you have a string like
1: string data = "52/00000012340056";
Your regex could be the following
1: Regex regex = new Regex(@"0+");
but take care about the zeros within the numbers. So you have to extend you regex like this:
1: Regex regex = new Regex(@"^\d+/0+");
If you run this expression over the sample data, the result looks like this:
1: string result = regex.Replace(data, String.Empty);
2: // result == "12340056";
Missing the prefix?
Extend the expressions with some named groups and use the matching values:
1: Regex regex = new Regex(@"^(?<prefix>\d+/)(0+)");
2: string result = regex.Replace(data, "${prefix}");
3: // result == "52/12340056";
That's it!
No comments:
Post a Comment