My latest favorite trick with regular expressions is to shortcut string formatting. We’ve all written some code like this:
if (/* string is not formatted a certain way */) { /* make it formatted that way */ }
Now, there’s nothing wrong with that code, but for simple examples you could do it all in one step with a regular expression!
Here are a few examples:
// remove "www." from a domain if one exists // domain.com -> domain.com // www.domain.com -> domain.com Regex.Replace(input, @"^(?:www.)?(.+)$", "$1"); // format phone number // 1234567890 -> 123-456-7890 // (123) 456-7890 -> 123-456-7890 // (123) 456 - 7890 -> 123-456-7890 Regex.Replace(input, @"^\(?(\d{3})\)?\s*(\d{3})\s*-?\s*(\d{4})$", "$1-$2-$3");
Yay, regular expressions!