Regular expressions are very helpful in finding patterns in text. C# and .Net supports regular expressions by a set of classes in the namespace System.Text.RegularExpressions. Instead of looping through the entire text and doing text comparison, regular expressions can do this job real fast.
The following samples demonstrate usage of regular expressions in C#
Regular expression sample to match text between specific characters. This sample displays all text between square brackets - [ and ]
string text = "Hello [JOHN], how are you and [TIMS] ? Did you meet [BILL] this week ?";
// Square brackets - [ ] are special characters in regular expression. So, they have to // be 'escaped' with a backslash. But backslash itself is a special character // in C# and so need to be use the escape character. So // we are using \\[ just to represent the [ and \\] to represent ]. string exp = "\\[(.*?)\\]"; Regex reg = new Regex( exp );
MatchCollection matches = Regex.Matches(text, exp, RegexOptions.IgnoreCase ); IEnumerator en = matches.GetEnumerator();
while ( en.MoveNext() ) { Match match = (Match) en.Current; MessageBox.Show( match.Value ); }
This sample displays all text between angle brackets - < and >.
string text = "Hello <JOHN>, how are you and <TIMS> ? Did you meet <BILL> this week ?";
string exp = "<(.*?)>"; Regex reg = new Regex( exp );
MatchCollection matches = Regex.Matches(text, exp, RegexOptions.IgnoreCase ); IEnumerator en = matches.GetEnumerator();
while ( en.MoveNext() ) { Match match = (Match) en.Current; MessageBox.Show( match.Value ); }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|