Introduction
A regular expression is one of the ways of searching substrings in strings. It is carried out by means of viewing a string in searches of some pattern. A well-known example can be symbols "*" and "?", used in command line DOS. The first one replaces a zero or more any symbols, the second - one any symbol. So, use of a pattern of search of type "text?.*" will find files textf.txt, text1.asp and others similar, but will not find text.txt or text.htm.
Usually, by means of regular expressions, three actions are carried out.
- Stock-taking corresponding a pattern to a substring.
- Search and delivery to the user corresponding a pattern of substrings.
- Replacement corresponding a pattern substrings.
In practice are applied three types regular machine expressions.
- DFA (Deterministic Finite-state Automaton - the determined final automatic devices) machines work linearly on time as do not require recoils (and never check one symbol twice). They can find the longest possible string possible. However, as DFA contains only a final condition, it cannot find the sample with the return reference and, because of the absence of designs with obvious expansion, does not catch subexpressions. They are used, for example, in awk, egrep or lex.
- Traditional NFA-machines (NonDeterministic Finite-state Automaton - not determined final automatic devices) uses "greedy" algorithm of recoil, checking all possible expansions of regular expression in the certain order and choosing the first suitable value. As traditional NFA designs the certain expansions of regular expression for the search of conformity, it can search
and back references. But because of recoils, the traditional NFA can check the same place sometimes. It as a result works more slowly. As traditional NFA accepts the first found conformity, it cannot find the longest ocurrences. Such mechanisms of regular expressions are used in Perl, Python, Emacs, Tcl and .NET. - POSIX NFA - machines are similar to traditional NFA-machines, except for "patience" - they continue the search, yet will not find the longest conformity. Therefore POSIX NFA-machines more slowly traditional and consequently it is impossible to force POSIX NFA to prefer shorter conformity long. One of the main advantages POSIX of the NFA-machine - presence of standard realization.
More often programmers use traditional NFA-machines as they are more exact than DFA or POSIX NFA. Though the time of their work grows in the worst case after an exhibitor, use of the samples reducing a level of ambiguity and limiting the depth of search with return (backtracking), allows operating their behavior, reducing the time of search up to comprehensible values.
.NET Regular Expressions
The Regexp classes are allowed to use regular expressions in .NET. All classes are contained in the System.Text.RegularExpressions assembly, and you will have to reference the assembly at compile time in order to build your application. For example, csc /r:System.Text.RegularExpressions.dll foo.cs will build the foo.exe assembly, with a reference to the System.Text.RegularExpressions assembly.
There are only six classes and one delegate which it is necessary to overview:
- Capture: Contains the results of a single match
- CaptureCollection: A sequence of Capture's
- Group: The result of a single group capture, inherits from Capture
- Match: The result of a single expression match, inherits from Group
- MatchCollection: A sequence of Match's
- MatchEvaluator: A delegate for use during replacement operations
- Regex: An instance of a compiled regular expression
The Regex class also contains several static methods:
- Escape: Escapes regex metacharacters within a string
- IsMatch: Methods return a boolean result if the supplied regular expression matches within the string
- Match: Methods return Match instance
- Matches: Methods return a list of Match as a collection
- Replace: Methods that replace the matched regular expressions with replacement strings
- Split: Methods return an array of strings determined by the expression
- Unescape: Unescapes any escaped characters within a string
Example
using System.Text.RegularExpressions;
using System;
namespace RegularExpressionsSample {
class Program {
static voidMain(string[] args) {
string regularExpression = "s[ia]mple";
string inputString = "Is it simple sample?";
Match m = Regex.Match(inputString, regularExpression);
Console.WriteLine("Match = " + m.ToString());
Console.WriteLine("Next match = " + m.NextMatch().ToString());
}
}
}
Output
Match = simple
Next match = sample
Regular Expression Options:
Regular Expression Options can be used in the constructor for the Regex class.
- RegexOptions.None - Specifies that no options are set.
- RegexOptions.IgnoreCase - Specifies case-insensitive matching.
- RegexOptions.Multiline - Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
- RegexOptions.Singleline - Specifies single-line mode. Changes the meaning of the dot (.) so it matches every character (instead of every character except \n).
- RegexOptions.ExplicitCapture - Specifies that the only valid captures are groups that are explicitly named or in the form (?<name>...).
- RegexOptions.IgnorePatternWhitespace - Eliminates unescaped white space from the pattern and enables comments marked with the hash sign (#).
- RegexOptions.Compiled - Specifies that the regular expression is compiled to an assembly. The regular expression will be faster to match but it takes more time to compile initially. This option (although tempting) should only be used when the expression will be used many times. e.g. in a foreach loop
- RegexOptions.ECMAScript - Enables ECMAScript-compliant behavior for the expression. This flag can be used only in conjunction with the IgnoreCase, Multiline, and Compiled flags. The use of this flag with any other flags results in an exception.
- RegexOptions.RightToLeft - Specifies that the search will be from right to left instead of from left to right.
Bases of the syntax of regular expressions
I will not begin to try to write the full directory on all symbols used in patterns of regular expressions. For this purpose there is MSDN. Here we will result in only the basic metasymbols. In double inverted commas the values which are given out by regular expressions, and in the unary - syntax of regular expressions will be used further.
In C#, metasymbols (those which you wish to use not as those but as actual symbols) should be covered by an escape-symbol \ as in C++ (in other languages can be different, for example, in VB it is not necessary). That is, to find "[" , it is necessary to write '\['.The symbol \ means, that the symbol following it is special symbol, a constant and so on. For example, 'n' means the letter "n." '\n' means a symbol of a new line. The sequence '\\' corresponds "\", and '\(' corresponds "(".
Classes of symbols (Character class)
Using square brackets, it is possible to specify a group of symbols (it name a class of symbols) for search. For example, the design 'b[ai]rge' would correspond to words "barge" and "birge", i.e. the words beginning with "b" which follow "a" or "i", and coming to an end on "rga". Probably and the return, that is, it is possible to specify symbols which should not contain in found substring. So, '[^1-6]' finds all symbols, except for figures from 1 up to 6. It is necessary to mention, that inside of a class of symbols '\b' designates a symbol backspace (deleting).
Quantifiers
If it is not known, how many signs should contain required substring, it is possible to use special symbols, called by an odd word quantifiers. For example, it is possible to write "hel+o", that will mean a word beginning with "he", with following for it one or the several "l", and coming to an end on "o". It is necessary to understand, that quantifier concerns to the previous expression, instead of a separate symbol.
| Symbol | Overview |
| * | Corresponds 0 or more occurrences of previous expression. For example, 'zo*' corresponds "z" and "zoo". |
| + | Corresponds 1 or more previous expressions. For example, 'zo+' corresponds "zo" and "zoo", but not "z". |
| ? | Corresponds 0 or 1 previous expressions. For example, 'do(es)?' corresponds "do" in "do" or "does". |
| *? | Corresponds 0 or more previous expressions as few characters as possible. For example, 'dog*?' corresponds "do" in "do" or "does" |
| +? | Corresponds 1 or more previous expressions as few characters as possible. For example, 'dog+?' corresponds "dog" in "dog" or "dogger". |
| {n} | n - the non-negative whole. Corresponds to the exact quantity of occurrences. For example, 'o{2}' will not find "o" in "Bob", but will find two "o" in "food". |
| {n,} | n - the non-negative whole. Corresponds to the occurrence repeated not less n of time. For example, 'o{2,}' does not find "o" in "Bob", but finds all "o" in "foooood". 'o{1,}' it is equivalent 'o+'. 'o{0,}' it is equivalent 'o*'. |
| {n,m} | m and n - non-negative integers, where n <= m. There correspond a minimum n and maximum m occurrences. For example, 'o{1,3}' finds three first "o" in "fooooood". 'o{0,1}' it is equivalent 'o?'. The blank space between a comma and figures is inadmissible. |
| | | When between two characters or groups, matches one or the other (this is called an alternating operation because it chooses among two alternatives). |
Table 1. Quantifiers.
The important feature of quantifiers '*' and '+' is their greed. They find everything, that can - instead of that is necessary.
Example.
Source string - "hello out there, how are you"
Regular expression - 'h.*o'
It means to search 'h' which any symbols which follow 'o' follow some. In a kind, probably, was available "hello", but it will be found "hello out there, how are you" - because of the greed of the regular expression looking not first, but last "o". To cure quantifier of greed it is possible, having added '?'. That is,
Source string - "hello out there, how are you"
Regular expression - 'h.*?o'
will find "hello", as it was necessary, as searches 'h' which any symbols follow some, up to the first met 'o'.
The ends and the beginnings of strings
Check has begun the ends or the end of a line is made by means of metasymbols ^ and $. For example, '^thing' corresponds to a line beginning with "thing". 'thing$' corresponds to a line which is coming to an end on "thing". These symbols work only at the included option 's'. At the switched off option 's' there is only an end and the beginning of the text. There is also a symbol \z, an exact end of a line.
Border of a word
Marcel BrinkkemperPosted May 22, 2019, 1:11 AM
Thanks, I have bookmarked your article. I keep forgetting how regular expressions work.
Ramzanali MominPosted Oct 30, 2018, 5:28 AM
Many thousand of thank for sharing this article
Navratna PawalePosted Nov 23, 2014, 10:17 AM
nice!!! wonderfull article...
Mujeeb KaithavelikakathuPosted Nov 10, 2006, 12:39 AM
This is a very helpful article