Regex Class

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"]);