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:

Modifier
Description
RegexOptions.IgnoreCase
case insensitive search
RegexOptions.Righttoleft
search from right to left
RegexOptions.Multiline
multiline matching


Regular Expression Syntax:

Syntax
Description
\d
Digit, 0,1,2 ... 9
\D
Not Digit
\s
Space
\S
Not Space
\w
Word
\W
Not Word
\t
Tab
\n
New line
^
Beginning of the string
$
End of the string
\
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]
a or b
[^ab]
Any character except a and b
[0-9]
All Digit
[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+
i at least one time
i*
i zero or more times
i?
i zero or 1 time
i{n}
i occurs n times in sequence
i{n1,n2}
i occurs n1 - n2 times in sequence
i{n,}
i occures >= n times
\0
NUL
\f
Form feed character
\r
Carriage return character
\v
Vertical tab
\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

endmemo.com © 2024  | Terms of Use | Privacy | Home