Regular Expression Language - Quick Reference
Updated: March 2012
A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs. For a brief introduction, see .NET Framework Regular Expressions.
Each section in this quick reference lists a particular category of characters, operators, and constructs that you can use to define regular expressions:
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes.
|
Escaped character |
Description |
Pattern |
Matches |
|---|---|---|---|
|
\a |
Matches a bell character, \u0007. |
\a |
"\u0007" in "Error!" + '\u0007' |
|
\b |
In a character class, matches a backspace, \u0008. |
[\b]{3,} |
"\b\b\b\b" in "\b\b\b\b" |
|
\t |
Matches a tab, \u0009. |
(\w+)\t |
"item1\t", "item2\t" in "item1\titem2\t" |
|
\r |
Matches a carriage return, \u000D. (\r is not equivalent to the newline character, \n.) |
\r\n(\w+) |
"\r\nThese" in "\r\nThese are\ntwo lines." |
|
\v |
Matches a vertical tab, \u000B. |
[\v]{2,} |
"\v\v\v" in "\v\v\v" |
|
\f |
Matches a form feed, \u000C. |
[\f]{2,} |
"\f\f\f" in "\f\f\f" |
|
\n |
Matches a new line, \u000A. |
\r\n(\w+) |
"\r\nThese" in "\r\nThese are\ntwo lines." |
|
\e |
Matches an escape, \u001B. |
\e |
"\x001B" in "\x001B" |
|
\ octal |
Uses octal representation to specify a character (octal consists of up to three digits). |
\w\040\w |
"a b", "c d" in "a bc d" |
|
\x hex |
Uses hexadecimal representation to specify a character (hex consists of exactly two digits). |
\w\x20\w |
"a b", "c d" in "a bc d" |
|
\c char |
Matches the ASCII control character that is specified by char. |
\cC |
"\x0003" in "\x0003" (Ctrl-C) |
|
\u0020 |
Matches a Unicode character by using hexadecimal representation (exactly four digits). |
\w\u0020\w |
"a b", "c d" in "a bc d" |
|
\ |
When followed by a character that is not recognized as an escaped character in this and other tables in this topic, matches that character. For example, \* is the same as \x2Aand \. is the same as \x2E. This allows the regular expression engine to disambiguate language elements (such as * or ?) and character literals (represented by \* or \?). |
\d+[\+-x\*]\d+\d+[\+-x\*\d+ |
"2+2" and "3*9" in "(2+2) * 3*9" |
A character class matches any one of a set of characters. Character classes include the language elements listed in the following table. For more information, see Character Classes.
|
Character class |
Description |
Pattern |
Matches |
|---|---|---|---|
|
[ character_group ] |
Matches any single character in character_group. By default, the match is case-sensitive. |
[ae] |
"a" in "gray" "a", "e" in "lane" |
|
[^ character_group ] |
Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive. |
[^aei] |
"r", "g", "n" in "reign" |
|
[ first - last ] |
Character range: Matches any single character in the range from first to last. |
[A-Z] |
"A", "B" in "AB123" |
|
. |
Wildcard: Matches any single character except \n. To match a literal period character (. or \u002E), you must precede it with the escape character (\.). |
a.e |
"ave" in "nave" "ate" in "water" |
|
\p{ name } |
Matches any single character in the Unicode general category or named block specified by name. |
\p{Lu} \p{IsCyrillic} |
"C", "L" in "City Lights" "Д", "Ж" in "ДЖem" |
|
\P{ name } |
Matches any single character that is not in the Unicode general category or named block specified by name. |
\P{Lu} \P{IsCyrillic} |
"i", "t", "y" in "City" "e", "m" in "ДЖem" |
|
\w |
Matches any word character. |
\w |
"I", "D", "A", "1", "3" in "ID A1.3" |
|
\W |
Matches any non-word character. |
\W |
" ", "." in "ID A1.3" |
|
\s |
Matches any white-space character. |
\w\s |
"D " in "ID A1.3" |
|
\S |
Matches any non-white-space character. |
\s\S |
" _" in "int __ctr" |
|
\d |
Matches any decimal digit. |
\d |
"4" in "4 = IV" |
|
\D |
Matches any character that is not a decimal digit. |
\D |
" ", "=", " ", "I", "V" in "4 = IV" |
Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The metacharacters listed in the following table are anchors. For more information, see Anchors in Regular Expressions.
|
Assertion |
Description |
Pattern |
Matches |
|---|---|---|---|
|
^ |
The match must start at the beginning of the string or line. |
^\d{3} |
"901" in "901-333-" |
|
$ |
The match must occur at the end of the string or before \n at the end of the line or string. |
-\d{3}$ |
"-333" in "-901-333" |
|
\A |
The match must occur at the start of the string. |
\A\d{3} |
"901" in "901-333-" |
|
\Z |
The match must occur at the end of the string or before \n at the end of the string. |
-\d{3}\Z |
"-333" in "-901-333" |
|
\z |
The match must occur at the end of the string. |
-\d{3}\z |
"-333" in "-901-333" |
|
\G |
The match must occur at the point where the previous match ended. |
\G\(\d\) |
"(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)" |
|
\b |
The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character. |
\b\w+\s\w+\b |
"them theme" "them them" in "them theme them them" |
|
\B |
The match must not occur on a \b boundary. |
\Bend\w*\b |
"ends", "ender" in "end sends endure lender" |
Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table. For more information, see Grouping Constructs.
|
Grouping construct |
Description |
Pattern |
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. |
(?<double>\w)\k<double> |
"ee" in "deep" |
|
(?< name1 - name2 > subexpression) |
Defines a balancing group definition. For more information, see the "Balancing Group Definition" section in Grouping Constructs. |
(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$ |
"((1-3)*(3-1))" in "3+2^((1-3)*(3-1))" |
|
(?: subexpression) |
Defines a noncapturing group. |
Write(?:Line)? |
"WriteLine" in "Console.WriteLine()" |
|
(?imnsx-imnsx: subexpression) |
Applies or disables the specified options within subexpression. For more information, see Regular Expression Options. |
A\d{2}(?i:\w+)\b |
"A12xl", "A12XL" in "A12xl A12XL a12xl" |
|
(?= subexpression) |
Zero-width positive lookahead assertion. |
\w+(?=\.) |
"is", "ran", and "out" in "He is. The dog ran. The sun is out." |
|
(?! subexpression) |
Zero-width negative lookahead assertion. |
\b(?!un)\w+\b |
"sure", "used" in "unsure sure unity used" |
|
(?<= subexpression) |
Zero-width positive lookbehind assertion. |
(?<=19)\d{2}\b |
"99", "50", "05" in "1851 1999 1950 1905 2003" |
|
(?<! subexpression) |
Zero-width negative lookbehind assertion. |
(?<!19)\d{2}\b |
"51", "03" in "1851 1999 1950 1905 2003" |
|
(?> subexpression) |
Nonbacktracking (or "greedy") subexpression. |
[13579](?>A+B+) |
"1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC" |
A quantifier specifies how many instances of the previous element (which can be a character, a group, or a character class) must be present in the input string for a match to occur. Quantifiers include the language elements listed in the following table. For more information, see Quantifiers.
|
Quantifier |
Description |
Pattern |
Matches |
|---|---|---|---|
|
* |
Matches the previous element zero or more times. |
\d*\.\d |
".0", "19.9", "219.9" |
|
+ |
Matches the previous element one or more times. |
"be+" |
"bee" in "been", "be" in "bent" |
|
? |
Matches the previous element zero or one time. |
"rai?n" |
"ran", "rain" |
|
{ n } |
Matches the previous element exactly n times. |
",\d{3}" |
",043" in "1,043.6", ",876", ",543", and ",210" in "9,876,543,210" |
|
{ n ,} |
Matches the previous element at least n times. |
"\d{2,}" |
"166", "29", "1930" |
|
{ n , m } |
Matches the previous element at least n times, but no more than m times. |
"\d{3,5}" |
"166", "17668" "19302" in "193024" |
|
*? |
Matches the previous element zero or more times, but as few times as possible. |
\d*?\.\d |
".0", "19.9", "219.9" |
|
+? |
Matches the previous element one or more times, but as few times as possible. |
"be+?" |
"be" in "been", "be" in "bent" |
|
?? |
Matches the previous element zero or one time, but as few times as possible. |
"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 previous element at least n times, but as few times as possible. |
"\d{2,}?" |
"166", "29", "1930" |
|
{ n , m }? |
Matches the previous element between n and m times, but as few times as possible. |
"\d{3,5}?" |
"166", "17668" "193", "024" in "193024" |
A backreference allows a previously matched subexpression to be identified subsequently in the same regular expression. The following table lists the backreference constructs supported by regular expressions in the .NET Framework. For more information, see Backreference Constructs.
|
Backreference construct |
Description |
Pattern |
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. |
(?<char>\w)\k<char> |
"ee" in "seek" |
Alternation constructs modify a regular expression to enable either/or matching. These constructs include the language elements listed in the following table. For more information, see Alternation Constructs.
|
Alternation construct |
Description |
Pattern |
Matches |
|---|---|---|---|
|
| |
Matches any one element separated by the vertical bar (|) character. |
th(e|is|at) |
"the", "this" in "this is the day. " |
|
(?( expression ) yes | no ) |
Matches yes if expression matches; otherwise, matches the optional no part. expression is interpreted as a zero-width assertion. |
(?(A)A\d{2}\b|\b\d{3}\b) |
"A10", "910" in "A10 C103 910" |
|
(?( name ) yes | no ) |
Matches yes if the named capture name has a match; otherwise, matches the optional no. |
(?<quoted>")?(?(quoted).+?"|\S+\s) |
Dogs.jpg, "Yiska playing.jpg" in "Dogs.jpg "Yiska playing.jpg"" |
Substitutions are regular expression language elements that are supported in replacement patterns. For more information, see Substitutions. The metacharacters listed in the following table are atomic zero-width assertions.
|
Character |
Description |
Pattern |
Replacement pattern |
Input string |
Result string |
|---|---|---|---|---|---|
|
$ number |
Substitutes the substring matched by group number. |
\b(\w+)(\s)(\w+)\b |
$3$2$1 |
"one two" |
"two one" |
|
${ name } |
Substitutes the substring matched by the named group name. |
\b(?<word1>\w+)(\s)(?<word2>\w+)\b |
${word2} ${word1} |
"one two" |
"two one" |
|
$$ |
Substitutes a literal "$". |
\b(\d+)\s?USD |
$$$1 |
"103 USD" |
"$103" |
|
$& |
Substitutes a copy of the whole match. |
(\$*(\d*(\.+\d+)?){1}) |
**$& |
"$1.30" |
"**$1.30**" |
|
$` |
Substitutes all the text of the input string before the match. |
B+ |
$` |
"AABBCC" |
"AAAACC" |
|
$' |
Substitutes all the text of the input string after the match. |
B+ |
$' |
"AABBCC" |
"AACCCC" |
|
$+ |
Substitutes the last group that was captured. |
B+(C+) |
$+ |
"AABBCCDD" |
AACCDD |
|
$_ |
Substitutes the entire input string. |
B+ |
$_ |
"AABBCC" |
"AAAABBCCCC" |
Miscellaneous constructs either modify a regular expression pattern or provide information about it. The following table lists the miscellaneous constructs supported by the .NET Framework. For more information, see Miscellaneous Constructs.
|
Construct |
Definition |
Example |
|---|---|---|
|
(?imnsx-imnsx) |
Sets or disables options such as case insensitivity in the middle of a pattern. For more information, see Regular Expression Options. |
\bA(?i)b\w+\b matches "ABA", "Able" in "ABA Able Act" |
|
(?# comment) |
Inline comment. The comment ends at the first closing parenthesis. |
\bA(?#Matches words starting with A)\w+\b |
|
# [to end of line] |
X-mode comment. The comment starts at an unescaped # and continues to the end of the line. |
(?x)\bA\w+\b#Matches words starting with A |
You have to escape them again when embedding them in a string, i.e. "\\134" and "\\\\", respectively.
Grouping Construct (?>subexpression) is not explained. The example of its usage is bad, because it works as well as pattern without this construct. Please, fix.
Nonbacktracking Subexpressions
This topic is intended as a quick reference page that lists each regular expression language element and provides a summary description; it is not intended to provide detailed documentation for each language element. Additional detail on nonbacktracking subexpressions can be found at http://msdn.microsoft.com/en-us/library/bs2twtah.aspx and http://msdn.microsoft.com/en-us/library/dsy130b4.aspx. It is true that the regular expression pattern behaves the same as a standard backtracking expression. Typically, though, that's why non-backtracking subexpressions are used; I'll explain that in a bit more detail below.
The following example illustrates the difference between a backtracking subexpression and a nonbacktracking subexpression. It tries to match zero or more consecutive word characters that end in a digit (a digit is also a word character). The C# code is:
string input = "123456";
string pattern1 = @"^\w*\d$";
Console.WriteLine(Regex.IsMatch(input, pattern1)); // Displays True.
string pattern2 = @"^(?>\w*)\d$";
Console.WriteLine(Regex.IsMatch(input, pattern2)); // Displays False
The Visual Basic code is:
Dim input As String = "123456"
Dim pattern1 As String = "^\w*\d$"
Console.WriteLine(Regex.IsMatch(input, pattern1)) ' Displays True.
Dim pattern2 As String = "^(?>\w*)\d$"
Console.WriteLine(Regex.IsMatch(input, pattern2)) ' Displays False
But most commonly, the (?>subexpression) language element is not used because its matching behavior is different from that of a backtracking subexpression. Instead, it is used because it matches the same input as a regular expression pattern that uses backtracking (in other words, backtracking is not important in identifying matches), but it is much more efficient in concluding that the input string does not match the regular expression pattern. Although we often focus on what a regular expression pattern matches, frequently what it does not match is even more important. This is because the .NET Framework provides an implementation of an NFA engine, and NFA engines must follow all possible paths through an input string before they can conclude that a match is unsuccessful. If a regular expression pattern includes nested quantifiers (such as (.+)*) and the input string is long, backtracking can extract a huge performance penalty. Usually in these cases, backtracking is also not essential to the success of the match. If this is the case, a nonbacktracking subexpression can be used, and performance will be improved enormously. This will be explained in greater detail in the Backtracking topic at http://msdn.microsoft.com/en-us/library/dsy130b4.aspx.
--Ron Petrusha
Developer Division User Education
Microsoft Corporation
- 2/17/2010
- thorn0
- 4/30/2010
- R Petrusha - MSFT
Plz can anyone explain me following two Function's Regular Expression.. plz explain the each part of Expression..
Explain Underline parts..
1.
void DumpHrefs(String inputString)
{
Regex r;
Match m;
r = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
RegexOptions.IgnoreCase|RegexOptions.Compiled);
for (m = r.Match(inputString); m.Success; m = m.NextMatch())
{
Console.WriteLine("Found href " + m.Groups[1] + " at "
+ m.Groups[1].Index);
}
}
2.
String Extension(String url)
{
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",
RegexOptions.Compiled);
return r.Match(url).Result("${proto}${port}");
}
Understanding the Regex Pattern
The first regular expression is explained in detail at http://msdn.microsoft.com/en-us/library/t9e807fx(VS.100).aspx. The second regular expression is explained in detail at http://msdn.microsoft.com/en-us/library/t9e807fx(VS.100).aspx. In both cases, the (?<name>expression) syntax is used to define a named group.
--Ron Petrusha
Developer Division User Education
Microsoft Corporation
- 2/10/2010
- Rizwan Majeed
- 2/24/2010
- R Petrusha - MSFT
could you provide a link to a quick reference page here, please?
i'm looking for the whitespace signifier and i can't find it.
the grouped pages are very, um, ordered (yay, geekout!) but pretty much useless if you don't know what category of element you're looking for.
Quick Reference Added
We've modified this topic so that, rather than linking to a set of topics that each document a particular category of language elements, it lists all of the language elements supported by regular expressions in the .NET Framework, and provides links to more detailed documentation (which is also in the process of revision and expansion). We've also provided an example of a regular expression and the matches that it finds in a particular string.
Let us know what you think about this new quick reference, and also how our regular expression documentation can be improved, by using the feedback mechanism at the top of the page.
--Ron Petrusha
Developer Division User Education
Microsoft Corporation
- 1/22/2008
- exotericist
- 10/27/2009
- R Petrusha - MSFT
You've just saved me hours of cutting, pasting, making SIMPLE examples (someone should run a course on that at Redmond) and reformatting, plus you've introduced a new resource: RegExLib.com.
Many thanks, OuTa-SyNc, and Hats off to you.
- 4/5/2009
- jumpin jack flash
- 4/6/2009
- Thomas Lee
Note also that a . in a character class [ ] loses "any character" meaning. Hence I propose that the following regex would be correct for ensuring that a filename was (any character other than dot slash backslash) followed by ".xls":
^[^./\\]+[.]xls$
- 3/25/2009
- caius jard
1) your matching pattern is two characters wide, \w & [^\.\\/], both of these must pass every time for your ()+ to work. All of your file names are of odd lengths, this will never work.
2) you tell it that the second character in the match must not be ., \, or /. As the ending works it's way down the string, it will eventually encounter a ., but you told the pattern that a dot is not acceptable, this causes the match to fail and the pattern unwinds to the last successful match. You the tell it that it must be followed by .xls, but when it unwinds, it goes back to the start of the last attempted match, which, in your examples, would be 'e.xls', 't.xls', and 'l.xls' respectively.
3) lastly, and this isn't causing failures, you match against (.xls){1}$, the {1} is unnecessary as every pattern will match only once unless you alter the match pattern with {}, ?, +, *, etc.
^([^\.\\/])+(.xls)$
This tells the engine to match everything except for ., \, and / as many times as possible (and at least once) starting from the beginning of the string, once it's exhausted all that it can, it must be followed by .xls which must also be at the end of the line.
http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1236361993&sr=8-1
I use expression ^([\w][^\.\\/])+(.xls){1}$ to catch invalid filenames: . \ or / are not wanted.
Some learned the following:
* VALID = excellfile.xls, excellexport.xls, excell.xls
* NOT VALID = excelfile.xls, excelexport.xls, excel.xls
Somehow it appears that the text excel is not excepted.
- 3/6/2009
- Jaap K