Core Concepts
Regular expressions utilize predefined special characters (metacharacters), ordinary characters, and their combinations to create "pattern strings." These pattern strings validate whether given strings match specific filtering logic or extract desired portions from strings. Regular expressions exhibit these characteristics:
- High flexibility, logical strength, and functionality
- Rapid complex string control through simple methods
- Relatively cryptic for newcomers
Metacharacters
Understanding metacharacters is essential for effective regular expression usage. The table below lists nearly all metacharacters with brief descriptions.
| Character | Description |
|---|---|
\\ |
Marks next character as special, literal, back reference, or octal escape. Example: \\n matches a newline character. |
^ |
Matches start of input string. With RegExp Multiline property set, also matches after \\n or \\r. |
$ |
Matches end of input string. With RegExp Multiline property set, also matches before \\n or \\r. |
\[\] |
Character set matching any character within brackets. Example: \[abc\] matches 'a' in "plain". |
\[^\] |
Negative character set matching any character not in brackets. Example: \[^abc\] matches 'd' in "abcd". |
- |
Acts as metacharacter in \[\], e.g., \[a-z\] matches lowercase letters. Otherwise normal character. |
. |
Matches any single character except \\n. To include \\n, use \[.\\n\] pattern. |
() |
Grouping, changes operator precedence. See " |
| ` | ` |
* |
Matches preceding subexpression zero or more times. Example: zo* matches "z" and "zoo". Equivalent to {0,}. |
+ |
Matches preceding subexpression one or more times. Example: 'zo+' matches "zo" and "zoo", not "z". Equivalent to {1,}. |
? |
Matches preceding subexpression zero or one time. Example: "do(es)?" matches "do" in "do" or "does". Equivalent to {0,1}. |
{n} |
Matches exactly n times. Example: 'o{2}' doesn't match 'o' in "Bob" but matches two o's in "food". |
{n,} |
Matches at least n times. Example: 'o{2,}' doesn't match 'o' in "Bob" but matches all o's in "fooood". |
{n,m} |
Matches between n and m times (n <= m). Example: "o{1,3}" matches first three 'o's in "fooooood". |
\\d |
Matches digit character. Equivalent to [0-9]. |
\\D |
Matches non-digit character. Equivalent to [^0-9]. |
\\w |
Matches word characters including underscore. Equivalent to [A-Za-z0-9_]. |
\\W |
Matches non-word characters. Equivalent to [^A-Za-z0-9_]. |
\\s |
Matches whitespace including space, tab, form feed, etc. Equivalent to [ \f\n\r\t\v]. |
\\S |
Matches non-whitespace characters. Equivalent to [^ \f\n\r\t\v]. |
\\b |
Matches word boundary. Example: 'er\b' matches 'er' in "never" but not in "verb". |
\\B |
Matches non-word boundary. Example: 'er\B' matches 'er' in "verb" but not in "never". |
\\f |
Matches form feed. Equivalent to \x0c and \cL. |
\\n |
Matches newline. Equivalent to \x0a and \cJ. |
\\r |
Matches carriage return. Equivalent to \x0d and \cM. |
\\t |
Matches tab. Equivalent to \x09 and \cI. |
\\v |
Matches vertical tab. Equivalent to \x0b and \cK. |
\\cx |
Matches control character specified by x. Example: \cM matches Control-M or carriage return. |
\\xn |
Matches n where n is hexadecimal escape value. Must be two digits. Example: '\x41' matches "A". |
\\un |
Matches n where n is Unicode character as four hex digits. Example: \u00A9 matches copyright symbol (?). |
\\nm |
If n and m are octal digits (0-7), \nm matches octal escape value nm. |
\\num |
If num is positive integer, indicates back reference to previous match. Example: '(.)\1' matches two consecutive identical characters. |
Regular Expressions in C#
Microsoft includes regex operation classes in System.Text.RegularExpressions namespace, so import this namespace to work with regular expressions in C#. In .NET Framework 4.5 and 4.6, this namespace contains 11 classes, 1 enumeration, and 1 delegate.
The Regex class is most commonly used. Its static methods include four frequent used ones for simple string matching and extraction tasks:
Regex.IsMatch() - Determines if match exists:
// Check if string is ID number
bool validationResult = Regex.IsMatch("370451659745368", @"^([0-9]{15}|[0-9]{17}[0-9xX])$");
Console.WriteLine(validationResult);
Regex.Matches() - Extracts multiple matches:
// Extract all numbers from string
MatchCollection results = Regex.Matches("2015年12月06日", @"\d+");
foreach (Match item in results)
{
Console.WriteLine(item.Value);
}
Regex.Replace() - Replaces matched content:
// Replace middle four digits of phone number with asterisks
string modifiedStr = Regex.Replace("13666688888", @"(\d{3})\d{4}(\d{4})", "$1****$2");
Console.WriteLine(modifiedStr);
Regex.Split() - Splits string based on matches:
// Extract all English names from string
string[] nameArray = Regex.Split("Jack123Tom345Mary345Amy", @"\d+");
foreach (string item in nameArray)
{
Console.WriteLine(item);
}
Common Regular Expression Patterns
01. Username/password validation: "^[a-zA-Z]\w{5,15}$" Format: Letter followed by [A-Z][a-z]_[0-9], 6-16 chars
02. Phone number validation: "^(\d{3,4}-)\d{7,8}$" Format: xxx/xxxx-xxxxxxx/xxxxxxxx
03. Mobile number validation: "^1[3|4|5|7|8][0-9]\d{8}$"
04. ID number validation (15 or 18 digits): "^([0-9]{15}|[0-9]{17}[0-9xX])$"
05. Email address validation: "^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
06. Alphanumeric only: "^[A-Za-z0-9]+$"
07. Integer or decimal: "^[0-9]+([.][0-9]+){0,1}$"
08. Numbers only: "^[0-9]*$"
09. Exactly n digits: "^\d{n}$"
10. At least n digits: "^\d{n,}$"
11. Between m-n digits: "^\d{m,n}$"
12. Zero or non-zero leading numbers: "^(0|[1-9][0-9]*)$"
13. Positive real number with 2 decimals: "^[0-9]+(.[0-9]{2})?$"
14. Positive real number with 1-3 decimals: "^[0-9]+(\.[0-9]{1,3})?$"
15. Non-zero positive integers: "^\+?[1-9][0-9]*$"
16. Non-zero negative integers: "^\-[1-9][0-9]*$"
17. Exactly 3 characters: "^.{3}$"
18. Alphabet letters only: "^[A-Za-z]+$"
19. Uppercase letters only: "^[A-Z]+$"
20. Lowercase letters only: "^[a-z]+$"
21. Contains special characters ^%&',;=?$": "[%&',;=?$\\^]+"
22. Chinese characters only: "^[\u4e00-\u9fa5]{0,}$"
23. URL validation: "^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"
24. Months of year: "^(0?[1-9]|1[0-2])$" Format: "01"-"09" and "10"-"12"
25. Days of month: "^((0?[1-9])|((1|2)[0-9])|30|31)$" Format: "01"-"09", "10"-"29", "30"-"31"
26. Date pattern: "\d{4}[年|\-|\.]\d{1-12}[月|\-|\.]\d{1-31}日?"
Comment: Matches most date formats
27. Double-byte characters: "[^[email protected]]"
Comment: Calculates string length (double-byte = 2, ASCII = 1)
28. Blank lines: "\n\s*\r"
Comment: Useful for deleting blank lines
29. HTML tags: "<(\S*?)[^>]*>.*?</>|<.*? />"
Comment: Basic HTML tag matching, limited effectiveness
30. Leading/trailing whitespace: "^\s*|\s*$"
Comment: Removes leading/trailing whitespace
31. URL patterns: "[a-zA-z]+://[^\s]*"
Comment: Basic URL matching
32. Valid account (letter start, 5-16 chars, alphanumeric underscore): "^[a-zA-Z][a-zA-Z0-9_]{4,15}$"
Comment: Useful for form validation
33. QQ numbers: "[1-9][0-9]{4,}"
Comment: QQ starts from 10000
34. Chinese postal code: "[1-9]\d{5}(?!\d)"
Comment: 6-digit postal codes
35. IP address: "([1-9]{1,3}\.){3}[1-9]"
Comment: Extracts IP addresses
36. MAC address: "([A-Fa-f0-9]{2}\:){5}[A-Fa-f0-9]"