C# Regular Expressions
A regular expression is a pattern that describes a shape of text. The Regex class tests, finds, and replaces text that fits a pattern.
Test Text with IsMatch
IsMatch searches the order line for one or more digits. The plain line has no digits, so it answers false.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string text = "Order 4521 ships on day 12";
string plain = "Ships on Monday";
Console.WriteLine(Regex.IsMatch(text, @"\d+"));
Console.WriteLine(Regex.IsMatch(plain, @"\d+"));
}
}Find and Count Numbers
Match returns the first run of digits in the text. Matches counts both runs of digits.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string text = "Order 4521 ships on day 12";
Match match = Regex.Match(text, @"\d+");
Console.WriteLine("First number: " + match.Value);
Console.WriteLine("Numbers: " + Regex.Matches(text, @"\d+").Count);
}
}Replace the Matches
Replace swaps each run of digits for a # sign. Both numbers in the line change.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string text = "Order 4521 ships on day 12";
Console.WriteLine(Regex.Replace(text, @"\d+", "#"));
}
}Example
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string text = "Code A12 and B340 are ready";
Match match = Regex.Match(text, @"\d+");
Console.WriteLine("First number: " + match.Value);
Console.WriteLine("Numbers: " + Regex.Matches(text, @"\d+").Count);
Console.WriteLine(Regex.Replace(text, @"\d+", "#"));
}
}Key points
- The System.Text.RegularExpressions namespace holds the Regex class.
- A verbatim string starts with @ and keeps backslashes as plain characters.
- In a pattern, \d matches one digit.
- A + sign after \d means one or more digits in a row.
- IsMatch reports whether the pattern appears in the text.
- Match finds the first match and Matches collects every match.
- Replace swaps each match for a replacement string.
In this example, the pattern matches runs of digits in the text. Match finds the first run, which is 12. Matches counts two runs in total. Replace swaps both runs for a # sign.
Note
A pattern describes a shape of text. It does not name one exact word or number.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the pattern @"\d+" match?