Regular Expression

What is Regular Expression in C#?


In C#, Regular Expression is a pattern which is used to parse and check whether the given input text is matching with the given pattern or not. In C#, Regular Expressions are generally termed as C# Regex. The .Net Framework provides a regular expression engine that allows the pattern matching. Patterns may consist of any character literals, operators or constructors.

C# provides a class termed as Regex which can be found in System.Text.RegularExpression namespace. This class will perform two things:

  • Parsing the inputing text for the regular expression pattern.
  • Identify the regular expression pattern in the given text.

Regex Syntax

There are many basic syntaxes like Quantifiers, Special Characters, Character Classes, Grouping & Alternatives are used for regular expressions.

Quantifiers:

SUB-EXPRESSION(GREEDY)SUB-EXPRESSION(LAZY)MATCHES
**?Used to match the preceding character zero or more times.
++?Used to match the preceding character one or more times.
???Used to match the preceding character zero or one time.
{n}{n}?Used to match the preceding character exactly n times.
{n, }{n, }?Used to match the preceding character at least n times.
{n, m}{n, m}?Used to match the preceding character from n to m times.

Special Characters:

SUB-EXPRESSIONMATCHES
^Word after this element matches at the beginning of the string or line.
$Word before this element matches at the end of the line or string.
.(Dot)Matches any character only once expect \n(new line).
\dIt is use to match the digit character.
\DIt is use to match the non-digit character.
\wIt is use to match any alphanumeric and underscore character.
\WIt is use to match the any non-word character.
\sIt is use to match the white-space characters.
\SIt is use to match the non white-space characters.
\nIt is use to match a newline character.

Character Classes:

SUB-EXPRESSIONMATCHES
[]It is used to match the range of character
[a-z]It is used to match any character in the range of a-z.
[^a-z]It is used to match any character not in the range of a-z.
\It is used to match Escaped special character.

Grouping and Alternatives:

SUB-EXPRESSIONMATCHES
()It is used for group expression
(a|b)| Operator is used for alternative either a or b.
(?(exp) yes|no)If expression is matched it gives yes otherwise it gives no.

Exa

Comments