C# Regex
C# Regex class contains various methods with regular expression.
using System.Text.RegularExpressions;
string str = "csharp regular expression";
Match m = Regex.Match(str, @"reg(.+)press");
if (m.Success)
{
str = m.Groups[1].ToString(); //ular ex
}
Regex.Replace() method replace a substring with specific pattern.
using System.Text.RegularExpressions;
string str = "csharp regular expression";
str = Regex.Replace(str, @"regular ", ""); //csharp expression
Regex.Split() method split the string into an array of substrings based on the specific pattern.
using System.Text.RegularExpressions;
using System.Windows.Forms;
string str = "csharp regular expression";
string[] arr = Regex.Split(str, " ");
string str2 = "";
for (int i = 0; i < arr.Length; i++)
{
str2 += i.ToString() + "," + arr[i] + ";";
}
MessageBox.Show(str2); //0,csharp;1,regular;2,expression;
Regular Expression Modifiers of RegexOptions:
RegexOptions.IgnoreCase
case insensitive search
RegexOptions.Righttoleft
search from right to left
RegexOptions.Multiline
multiline matching
Regular Expression Syntax:
\
Escape special characters, e.g. \\ is "\", \+ is "+"
|
Alternation match. e.g. /(e|d)n/ matches "en" and "dn"
•
Any character, except \n or line terminator
[^ab]
Any character except a and b
[A-Z]
All uppercase A to Z letters
[a-z]
All lowercase a to z letters
[A-z]
All Uppercase and lowercase a to z letters
i{n}
i occurs n times in sequence
i{n1,n2}
i occurs n1 - n2 times in sequence
i{n,}
i occures >= n times
\r
Carriage return character
\xhhhh
Unicode with 4 characters of hexadecimal code hhhh
\xhh
Character with 2 characters of hexadecimal code hh
?=i
Lookahead matches only if i is followed
""
Use " to escape " character
\$
Use \ to escape other special characters, e.g. $, ?, *, ., ', &, +, - etc