Regex Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- Used to work with regular expressions.
- A good free tool to read and create regexs is Expresso.
- There are many good tutorials around.
Good practice
- Always include the ^ and $ when matching expressions.
- Without these you will simply check if a string contains the regex, which can expose a security vulnerability.
- See the example below for an example on what can happen when forgetting the leading ^.
- Start your regex with the @ sign 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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



