Replacing string or substrings with Regular Expressions in C#
Often C# developer uses String.Replace in order to substitute string with another string. However, regular expressions can do it just as easily. One good example is to reverse Date from US to UK standard
String ConvertDate(String input)
{
returnRegex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
String ConvertDate(String input)
{
returnRegex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
As we all remember <month> is a backreference that we use to get everything that is positioned after it and then we reconstruct new string with them.
Regular expressions uses substitutions
Character | Description Substitution |
---|---|
$number | last substring matched. |
${name} | last substring matched. |
$$ | single "$" literal. |
$& | copy of the entire match itself. |
$` | text of the input before the match. |
$' | text of the input after the match. |
$+ | last group captured. |
$_ | entire input string. |
We can also use Regular expression to constraint text string to certain format. For example, Microsoft uses this "[a–zA–Z'`–´\s]{1,40}" as the most optimized Regular expression for names.