Monday, December 7, 2009

Advanced Stringreplace

While handling string data it's often needed to replace or cut a partial string. String.Replace is such a simple method to replace values in C#.

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:
and some tools to check you patterns against data:

And now, time for some excamples.

Assume you have a string like
   1:  string data = "52/00000012340056";
and have to replace the zeros after the slash.

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