Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 32 / 68

Intro to Regular Expressions (Pattern Matching)

In this lesson you will learn the basics of pattern matching with regular expressions in C#, so you can check whether text follows a given format. This is for anyone searching for "C# regular expressions how to use".

A regular expression is a special notation that describes the shape of a string. You can specify a pattern such as "three digits, a hyphen, then four digits", check whether text matches it, and pull out the matching part. C# provides System.Text.RegularExpressions.Regex.

The sample code extracts something that looks like a phone number with Regex.Match(text, @"\d{3}-\d{4}-\d{4}") and checks whether a string is all digits with Regex.IsMatch("12345", @"^\d+$"). Prefixing a string with @ (a verbatim string) lets you write backslashes literally, which reads much better.

A common stumbling block for beginners is learning what all the symbols mean. It looks like nothing but punctuation at first, but it is a powerful tool that pays off in practice, for example when validating email formats.

In real-world development, the .NET regular expression engine is feature-rich and handles complex patterns flexibly, so it turns up in validation and many other places.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)