Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Regular Expressions

C# Regular Expressions

Regular expressions is a search formula used to describe and match text patterns. Simply put, you can think of it as a special wildcard language used to precisely find, validate, or replace content in strings.

For example, determining whether user input is a valid email address or phone number, or extracting all dates from a piece of text - these are typical application scenarios of regular expressions.

The .NET framework has a fully-featured built-in regular expression engine, provided through the System.Text.RegularExpressions namespace.

A regular expression pattern consists of one or more characters, operators, and constructs, which together describe the rules for the text to be matched.

If you don't understand regular expressions yet, you can first read ourRegular Expressions - Tutorial。

Defining Regular Expressions

A regular expression consists of the following types of building blocks, each responsible for a different matching function:

Character Escapes

In regular expressions, the backslash character (\) has two purposes: first, it turns theordinary character that follows it into a special meaning(such as \n (indicating a newline), and second, itescapes a special character into a literal character(such as \. (matching a real period instead of "any character").

A common mistake for beginners: in C# strings,\ is itself an escape character, so if you write in a regex \d, in a C# string you must write "\\d", or use a verbatim string @"\d"(recommended).

The following table lists commonly used escape characters:

Escape character Description Mode Matches
\a Matches the alert (bell) character \u0007. \a "\u0007" in "Warning!" + '\u0007'
\b In a character class, matches the backspace key \u0008. (Note: outside a character class, \b denotes a word boundary; see the "Anchors" section) [\b]{3,} "\b\b\b\b" in "\b\b\b\b"
\t Matches the tab character \u0009. Often used to match tab-separated text. (\w+)\t "Name\t" and "Addr\t" in "Name\tAddr\t"
\r Matches the carriage return character \u000D. (\r is not equivalent to the newline character \n. Windows line breaks are usually \r\n) \r\n(\w+) "\r\nHello" in "\r\nHello\nWorld."
\v Matches the vertical tab character \u000B. [\v]{2,} "\v\v\v" in "\v\v\v"
\f Matches the form feed character \u000C. [\f]{2,} "\f\f\f" in "\f\f\f"
\n Matches the newline character \u000A. Line endings on Unix/Linux systems usually consist of only \n. \r\n(\w+) "\r\nHello" in "\r\nHello\nWorld."
\e Matches the escape character \u001B. \e "\x001B" in "\x001B"
\ nnn Specifies a character using octal notation (nnn consists of two to three digits). \w\040\w "a b" and "c d" in "a bc d"
\x nn Specifies a character using hexadecimal notation (nn consists of exactly two digits). \w\x20\w "a b" and "c d" in "a bc d"
**\c X \c x ** Matches the ASCII control character specified by X or x, where X or x is the letter of the control character. \cC "\x0003" in "\x0003" (Ctrl-C)
\u nnnn Matches a Unicode character using hexadecimal notation (a four-digit number represented by nnnn). \w\u0020\w "a b" and "c d" in "a bc d"
** When followed by an unrecognized escape character, matches that character. \d+[+-x*]\d+\d+[+-x*\d+ "(2+2) * 39" - "2+2" and "39"

Character class

Character classes are used to matchany one of a "certain class" of characters. For example [aeiou] matches any vowel,\d matches any digit. This is one of the most commonly used basic features in regular expressions.

The following table lists character classes:

Character class Description Mode Matches
[character_group] Matches any single character in character_group. By default, matching is case-sensitive. [mn] "m" in "mat", and "m" and "n" in "moon"
[^character_group] Negation: matches any single character not in character_group. By default, characters in character_group are case-sensitive. [^aei] "v" and "l" in "avail"
[ first - last ] Character range: matches any single character in the range from first to last. [b-d] [b-d]irds can match Birds, Cirds, Dirds
. Wildcard: matches any single character except \n.
To match a literal period character (. or \u002E), you must place an escape character before it. a.e "ave" in "have", "ate" in "mate"
\p{ name } The difference between name Matches any single character in the specified Unicode general category or named block. \p{Lu} "C" and "L" in "City Lights"
\P{ name } Matches any single character not in the specified Unicode general category or named block. name Matches any single character in the specified Unicode general category or named block. \P{Lu} "i", "t", and "y" in "City"
\w Matches any word character (letter, digit, underscore). Equivalent to [a-zA-Z0-9_] (within the ASCII range). \w "R", "o", "m", and "1" in "Room#1"
\W Matches any non-word character. It is the negation of \w. \W "#" in "Room#1"
\s Matches any whitespace character (space, tab, newline, etc.). \w\s "D " in "ID A1.3"
\S Matches any non-whitespace character. It is the negation of \s. \s\S " _" in "int __ctr"
\d Matches any decimal digit. Equivalent to [0-9]. \d "4" in "4 = IV"
\D Matches any character that is not a decimal digit. It is the negation of \d. \D " ", "=", " ", "I", and "V" in "4 = IV"

Anchors

Anchors (also called "anchor points") do not match any specific character; instead, they match a certain position in the stringPosition. They are "zero-width", consuming no characters; they only assert that the current position satisfies a certain condition.

For example ^\d{3} indicates "three digits at the beginning of the string",\b indicates "the boundary between a word character and a non-word character".

The following table lists anchors:

Assertion Description Mode Matches
^ The match must start at the beginning of the string or line. ^\d{3} "567" in "567-777-"
$ The match must occur at the end of the string, or before a newline at the end of the string or line. \n before. -\d{4}$ "-2012" in "8-12-2012"
\A The match must occur at the beginning of the string (unaffected by multiline mode; always the beginning of the entire string). \A\w{4} "Code" in "Code-007-"
\Z The match must occur at the end of the string, or before a newline at the end of the string. \n before. -\d{3}\Z "-007" in "Bond-901-007"
\z The match must occur at the end of the string (strict end; no trailing \n allowed). -\d{3}\z "-333" in "-901-333"
\G The match must occur at the point where the previous match ended. Often used in consecutive matching scenarios. \G(\d) "(1)(3)(5)7- "(1)", "(3)", and "(5)"
\b Matches a word boundary, that is, the position between a word character and a space. er\b matches "er" in "never", but not "er" in "verb".
\B Matches a non-word boundary. er\B matches "er" in "verb", but not "er" in "never".

Grouping Constructs

Grouping constructs use parentheses ( ) to enclose part of a regular expression, forming a subexpression. Grouping has two main purposes:

This part is somewhat difficult to understand; you can read Regular Expressions - Alternation 、Lookahead and lookbehind assertions in regular expressions. to help understand it.

The following table lists grouping constructs:

Grouping Constructs Description Mode Matches
( subexpression ) Captures the matched subexpression and assigns it a zero-based ordinal number. (\w)\1 "ee" in "deep"
(?< name >subexpression) Captures the matched subexpression into a named group. Named groups are more readable than numeric numbering and are recommended for complex regular expressions. (?< double>\w)\k< double> "ee" in "deep"
(?< name1 -name2 >subexpression) Defines a balancing group definition. Used to match nested structures (such as paired parentheses); an advanced feature. (((?'Open'()[^()])+((?'Close-Open'))[^()])+)*(?(Open)(?!))$ "3+2^((1-3)"((1-3)" in "(3-1))"(3-1))"
(?: subexpression) Defines a non-capturing group. Use when you only need grouping (to limit scope) without saving the matched content; slightly better performance than capturing groups. Write(?:Line)? "WriteLine" in "Console.WriteLine()"
(?imnsx-imnsx:subexpression) Applies or disables the subexpression options specified in it. A\d{2}(?i:\w+)\b "A12xl" and "A12XL" in "A12xl A12XL a12xl"
(?= subexpression) Zero-width positive lookahead assertion. Matches a position followed by subexpression, but consumes no characters. \w+(?=.) "is", "ran", and "out" in "He is. The dog ran. The sun is out."
(?! subexpression) Zero-width negative lookahead assertion. Matches a position not followed by subexpression. \b(?!un)\w+\b "sure" and "used" in "unsure sure unity used"
(?<=subexpression) Zero-width positive lookbehind assertion. Matches a position preceded by subexpression. (?<=19)\d{2}\b "99", "50", and "05" in "1851 1999 1950 1905 2003"
(? Zero-width negative lookbehind assertion. Matches a position not preceded by subexpression. (? "man" in "Hi woman Hi man"
(?> subexpression) Non-backtracking (atomic group) subexpression. Once a match succeeds, backtracking is not allowed, which can improve performance in some scenarios. 13579 "1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC"

Example

using

System

;

using

System.Text.RegularExpressions

;

public

class

Example

{

   

public

static

void

Main

(

)

   

{

     

string

input

=

"1851 1999 1950 1905 2003"

;

     

string

pattern

=

@"(?<=19)\d{2}\b"

;

     

foreach

(

Match match

in

Regex

.

Matches

(

input, pattern

)

)

         Console

.

WriteLine

(

match

.

Value

)

;

   

}

}

Run Example »

Qualifier

A quantifier specifies that the preceding element (a character, character class, or group) must appearhow many timesfor the match to succeed.

Quantifiers aregreedyby default, matching as many characters as possible. Adding a ? ? after a quantifier changes it to **lazy (non-greedy)** mode, matching as few characters as possible. Beginners can first master *、+、?、{n} these four basic quantifiers.

The following table lists quantifiers:

Qualifier Description Mode Matches
***** Matches the preceding element zero or more times. (Zero times also counts as a match.) \d*.\d ".0"、 "19.9"、 "219.9"
+ Matches the preceding element one or more times. (At least once.) "be+" "bee" in "been", "be" in "bent"
? Matches the preceding element zero or one time. (The element is optional.) "rai?n" "ran"、 "rain"
{ n } Matches the preceding element exactly n times. ",\d{3}" ",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,} Matches the preceding element at least n times. "\d{2,}" "166"、 "29"、 "1930"
{ n , m } Matches the preceding element at least n times, but no more than m times. "\d{3,5}" "19302" in "166", "17668", "193024"
*? Matches the preceding element zero or more times, but as few times as possible (lazy mode). \d*?.\d ".0"、 "19.9"、 "219.9"
+? Matches the preceding element one or more times, but as few times as possible (lazy mode). "be+?" "be" in "been", "be" in "bent"
?? Matches the preceding element zero or one time, but as few times as possible (lazy mode). "rai??n" "ran"、 "rain"
{ n }? Matches the leading element exactly n times. ",\d{3}?" ",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210"
{ n ,}? Matches the preceding element at least n times, but as few times as possible. "\d{2,}?" "166", "29", and "1930"
{ n , m }? Matches the preceding element between n and m times, but as few times as possible. "\d{3,5}?" "193" and "024" in "166", "17668", "193024"

Backreference Constructs

A backreference allows you to reference, within the same regular expression,previously captured group contentfor matching again. For example, using (\w)\1 can find consecutive repeated characters such as "ee" and "ll".

The following table lists backreference constructs:

Backreference Constructs Description Mode Matches
\ number Backreference. Matches the value of a numbered subexpression. (\w)\1 "ee" in "seek"
\k< name > Named backreference. Matches the value of a named expression. More readable than numeric references and recommended. (?< char>\w)\k< char> "ee" in "seek"

Alternation Constructs

Alternation constructs use the vertical bar | to implement "or" logic, allowing a regular expression to match any one of multiple candidate patterns. Similar to conditional statements in programming languages. || new operator.

The following table lists alternation constructs:

Alternation Constructs Description Mode Matches
| Matches any one of the elements separated by the vertical bar (|) character. th(e|is|at) "the" and "this" in "this is the day. "
(?( expression )yes | no ) If the regular expression pattern is matched as specified by expression, then match yes; otherwise, match the optional no part. expression is interpreted as a zero-width assertion. (?(A)A\d{2}\b|\b\d{3}\b) "A10" and "910" in "A10 C103 910"
(?( name )yes | no ) If name or a named or numbered capture group has a match, then match yes; otherwise, match the optional no。 (?< quoted>")?(?(quoted).+?"|\S+\s) Dogs.jpg and "Yiska playing.jpg" in "Dogs.jpg "Yiska playing.jpg""

Replacement

Replacement syntax is used in the Regex.Replace() method'sreplacement pattern string, where you can add a number or name after $ $ to reference previously captured group content, enabling flexible text restructuring.

The following table lists the characters used in replacement:

Character Description Mode Replacement pattern Input string Result string
**$**number Replaces by group number the matched substring. \b(\w+)(\s)(\w+)\b $3$2$1 "one two" "two one"
${name} Replaces by named group name the matched substring. \b(?< word1>\w+)(\s)(?< word2>\w+)\b ${word2} ${word1} "one two" "two one"
$$ Replaces the "$" character. \b(\d+)\s?USD $$$1 "103 USD" "$103"
$& Replaces with a copy of the entire match. ($(\d(.+\d+)?){1}) **$& "$1.30" "**$1.30"
$` Replaces all text in the input string before the match. B+ $` "AABBCC" "AAAACC"
$' Replaces all text in the input string after the match. B+ $' "AABBCC" "AACCCC"
$+ Replaces the last captured group. B+(C+) $+ "AABBCCDD" AACCDD
$_ Replaces the entire input string. B+ $_ "AABBCC" "AAAABBCCCC"

Miscellaneous Constructs

The following table lists various miscellaneous constructs:

to construct Description Example
(?imnsx-imnsx) Sets or disables options such as case-insensitivity in the middle of a pattern. \bA(?i)b\w+\b matches "ABA" and "Able" in "ABA Able Act"
(?#comment) Inline comment. The comment terminates at the first right parenthesis. \bA(?#matches words starting with A)\w+\b
**# **[end of line] This comment starts with an unescaped # and continues to the end of the line. (?x)\bA\w+\b#matches words starting with A

Regex Class

The Regex class is the core class for using regular expressions in .NET, located in the System.Text.RegularExpressions namespace. Before using it, you need to add the following at the top of the file:

using System.Text.RegularExpressions;

The following table lists some commonly used methods of the Regex class:

No. Method & Description
1 **public bool IsMatch( string input ) **
Determines whether the input string contains content matching the regular expression pattern. Commonly used for form validation, such as validating phone numbers and email formats.
2 **public bool IsMatch( string input, int startat ) **
Starts the match from a specified starting position in the string.
3 **public static bool IsMatch( string input, string pattern ) **
A static method that does not require creating a Regex object first; you pass the pattern string directly for matching. Suitable for one-time use.
4 **public MatchCollection Matches( string input ) **
Searches the input string for all matches, returning a MatchCollection that can be iterated with foreach.
5 **public string Replace( string input, string replacement ) **
Replaces all content in the input string that matches the regular expression pattern with a specified string.
6 **public string[] Split( string input ) **
Splits the input string into an array of substrings according to delimiters defined by the regular expression pattern. More flexible than string.Split(), supporting complex splitting rules.

For the complete list of properties of the Regex class, please refer to Microsoft's C# documentation.

Example 1

The following example matches words starting with 'S':

Analysis:\b \b is a word boundary,S S matches the uppercase letter S,\S* \S* matches zero or more non-whitespace characters; together they mean "a complete word starting with S".

Example

using

System

;

using

System.Text.RegularExpressions

;

namespace

RegExApplication

{

   

class

Program

   

{

     

private

static

void

showMatch

(

string

text,

string

expr

)

     

{

         Console

.

WriteLine

(

"The Expression: "

expr

)

;

         MatchCollection mc

=

Regex

.

Matches

(

text, expr

)

;

         

foreach

(

Match m

in

mc

)

         

{

            Console

.

WriteLine

(

m

)

;

         

}

     

}

     

static

void

Main

(

string

[

]

args

)

     

{

         

string

str

=

"A Thousand Splendid Suns"

;

         Console

.

WriteLine

(

"Matching words that start with 'S': "

)

;

         showMatch

(

str,

@"\bS\S*"

)

;

         Console

.

ReadKey

(

)

;

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



Matching words that start with 'S':

The Expression: \bS\S*

Splendid

Suns

Example 2

The following example matches words starting with 'm' and ending with 'e':

Analysis:\bm \b matches words starting with m,\S* \w* matches any non-whitespace characters in between,e\b e requires ending with e followed by a word boundary; together they find all words starting with m and ending with e.

Example

using

System

;

using

System.Text.RegularExpressions

;

namespace

RegExApplication

{

   

class

Program

   

{

     

private

static

void

showMatch

(

string

text,

string

expr

)

     

{

         Console

.

WriteLine

(

"The Expression: "

expr

)

;

         MatchCollection mc

=

Regex

.

Matches

(

text, expr

)

;

         

foreach

(

Match m

in

mc

)

         

{

            Console

.

WriteLine

(

m

)

;

         

}

     

}

     

static

void

Main

(

string

[

]

args

)

     

{

         

string

str

=

"make maze and manage to measure it"

;

         Console

.

WriteLine

(

"Matching words start with 'm' and ends with 'e':"

)

;

         showMatch

(

str,

@"\bm\S*e\b"

)

;

         Console

.

ReadKey

(

)

;

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



Matching words start with 'm' and ends with 'e':

The Expression: \bm\S*e\b

make

maze

manage

measure

Example 3

The following example replaces extra spaces:

Analysis:\\s+ \s+ matches one or more consecutive whitespace characters (spaces, tabs, etc.) and replaces them all with a single space, thereby collapsing extra whitespace.

Example

using

System

;

using

System.Text.RegularExpressions

;

namespace

RegExApplication

{

   

class

Program

   

{

     

static

void

Main

(

string

[

]

args

)

     

{

         

string

input

=

"Hello   World   "

;

         

string

pattern

=

"\s+"

;

         

string

replacement

=

" "

;

         Regex rgx

=

new

Regex

(

pattern

)

;

         

string

result

=

rgx

.

Replace

(

input, replacement

)

;

         Console

.

WriteLine

(

"Original String: {0}"

, input

)

;

         Console

.

WriteLine

(

"Replacement String: {0}"

, result

)

;

   

         Console

.

ReadKey

(

)

;

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



Original String: Hello   World   

Replacement String: Hello World   

GeneratedRegex: Source Generator Optimization (.NET 7+)

Starting with .NET 7, C# introduced the [GeneratedRegex] attribute (source generator), which is an important upgrade to the traditional Regex class, designed specifically forperformance-sensitiveorand repeatedly usedregular expression scenarios.

Problems with the Traditional Approach

When using the traditional new Regex(pattern) , the parsing and compilation of the regular expression occur atRuntime, with overhead on every creation. Although you can use RegexOptions.Compiled to improve runtime speed, compilation still occurs at runtime and increases startup time and memory usage.

Traditional Approach

using

System.Text.RegularExpressions

;

// Approach 1: re-parse on every call (slowest)

bool

isMatch

=

Regex

.

IsMatch

(

input,

@"\d{4}-\d{2}-\d{2}"

)

;

// Approach 2: static field + Compiled (common optimization practice)

private

static

readonly

Regex DateRegex

=

new

Regex

(

@"\d{4}-\d{2}-\d{2}"

, RegexOptions

.

Compiled

)

;

Using GeneratedRegex

Use [GeneratedRegex] attribute, the compiler atCompile Stagecompile time generates the regular expression directly into efficient C# code, with no runtime parsing or compilation.

Requirements: .NET 7 or higher is needed, and the method must be partial and the containing class must also be partial class.

Basic Usage of GeneratedRegex

using

System

;

using

System.Text.RegularExpressions

;

namespace

RegExApplication

{

   

// The class must be declared as partial

   

partial

class

Program

   

{

     

// Use the [GeneratedRegex] attribute; the compiler automatically generates the implementation

     

[

GeneratedRegex

(

@"\d{4}-\d{2}-\d{2}"

)

]

     

private

static

partial

Regex DateRegex

(

)

;

     

// You can also add options, such as ignoring case

     

[

GeneratedRegex

(

@"\bS\S*"

, RegexOptions

.

IgnoreCase

)

]

     

private

static

partial

Regex StartsWithSRegex

(

)

;

     

static

void

Main

(

string

[

]

args

)

     

{

         

string

input

=

"Today is 2024-06-18, next event: 2025-01-01"

;

         

// Use it like a normal method; it returns a Regex instance

         

foreach

(

Match m

in

DateRegex

(

)

.

Matches

(

input

)

)

         

{

            Console

.

WriteLine

(

"Date found: "

m

.

Value

)

;

         

}

         

// Verify whether there is a match

         Console

.

WriteLine

(

StartsWithSRegex

(

)

.

IsMatch

(

"Splendid"

)

)

;

// True

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



找到日期:2024-06-18

找到日期:2025-01-01

True

GeneratedRegex vs. Traditional Regex

The following table compares the two approaches across multiple dimensions to help you choose the appropriate usage:

Comparison Dimensions Traditional Regex GeneratedRegex (Source Generator) Recommend
Minimum version requirement Supported in all versions of .NET Framework / .NET Core .NET 7 and above —
Compilation timing Runtime parsing and compilation Code generated by the Roslyn source generator during the build phase (build time) GeneratedRegex
Execution performance Normal: slower; with the Compiled option: faster, but with high startup overhead Fastest, close to the performance of hand-written code, with no startup overhead GeneratedRegex
Memory Usage Compiled mode generates IL code, with higher memory usage Generates ordinary C# code, which is more memory-friendly GeneratedRegex
AOT compatibility RegexOptions.Compiled is not compatible with AOT (ahead-of-time compilation) Fully compatible with Native AOT, suitable for publishing standalone applications GeneratedRegex
Code Readability The pattern string is written directly in the code, which is more intuitive Requires defining a partial method, making the code structure slightly more complex Traditional Regex (simple scenarios)
Dynamic patterns Supported; the pattern can be a runtime variable Not supported; the pattern must be a compile-time constant Traditional Regex (dynamic scenarios)
Debugging support Normal The generated code can be viewed and debugged directly, making it more transparent GeneratedRegex
Applicable scenarios One-time use, dynamic patterns, older .NET projects High-frequency calls, performance-sensitive, AOT publishing, newer .NET projects Depends on the scenario

Usage recommendation

Example: Using GeneratedRegex to Validate Email Format

using

System

;

using

System.Text.RegularExpressions

;

partial

class

EmailValidator

{

   

// Define the email validation regex, ignoring case

   

[

GeneratedRegex

(

@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"

, RegexOptions

.

IgnoreCase

)

]

   

private

static

partial

Regex EmailRegex

(

)

;

   

public

static

bool

IsValidEmail

(

string

email

)

   

{

     

return

EmailRegex

(

)

.

IsMatch

(

email

)

;

   

}

   

static

void

Main

(

string

[

]

args

)

   

{

     

string

[

]

emails

=

{

"user@example.com"

,

"bad-email"

,

"hello@world.org"

,

"missing@dot"

}

;

     

foreach

(

var

email

in

emails

)

     

{

         Console

.

WriteLine

(

$

"{email}: {(IsValidEmail(email) ? "

Valid

" : "

Invalid

")}"

)

;

     

}

   

}

}

When the code above is compiled and executed, it produces the following result:



user@example.com: 有效

bad-email: 无效

hello@world.org: 有效

missing@dot: 无效