Overview
- Used to work with regular expressions.
- A good free tool to read and create regexes is Expresso.
- There are many good tutorials around.
Good practice
- Always include ^ and $ when validating input.
- Without these you will simply check if a string contains the regex, which can expose a security vulnerability.
- See the example below of what can happen when forgetting the leading ^.
- Prefix your regex string with @ (a verbatim string) for readability, instead of having to escape backslashes.
Examples
Checking Input
string regex = @"^\d{5}$";
Console.WriteLine(Regex.IsMatch("12345", regex) ? "Matches!" : "No match");
Console.WriteLine(Regex.IsMatch("1234", regex) ? "Matches!" : "No match");
Console.WriteLine(Regex.IsMatch("DROP DATABASE YourApp; -- 12345", @"\d{5}$") ? "Matches!" : "No match");
Replacing Input
string input = "The dog ate a bone.";
string regex = @"^The (?<animal>\w+)\b ate (?<food>.+)\.$";
Console.WriteLine(Regex.Replace(input, regex, "Animal: ${animal}, Food: ${food}"));
Using Groups
Match x = Regex.Match("Wim", "(?<FirstLetter>.).*");
Console.WriteLine(x.Groups["FirstLetter"]);
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




