Tuesday 19 June 2012

CSharp: How to replace with Regex

Question:
How to replace a set of chars by another character using regular expressions in C#?


Answer:
In this case you can simply use the static method Replace()  on the Regex class and pass in an input string where you want to replace, a pattern and a replacement.

Here is an example
/// 
/// Replaces all occurrences of groups of one or more natural word breakers inside the code paths by '_' (underscore, under-bar)
/// 
/// 
/// 
private string ReplaceWordBreakers(string theCodeNomen)
{
   string find = @"\W+"; // one or more non-word char
   string replace = "_";
   string result = Regex.Replace(theCodeNomen, find, replace);
   return result;
}



No comments: