Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
5.11 Regular Expressions<br />
Use of regular expressions can simplify much of the hard work of string processing.<br />
We can specify patterns that get matched against input strings.<br />
Some simple patterns:<br />
Simple Patterns<br />
.<br />
Matches any character<br />
\s<br />
Matches any white space character<br />
\S<br />
Matches any non white space characters<br />
\d<br />
Matches any digit<br />
and<br />
Matches the word and<br />
.*<br />
Matches any number of any characters – "greedy" match<br />
^<br />
Matches the beginning of the search string<br />
$<br />
Matches the end of the search string<br />
duction <strong>to</strong> .NET<br />
<strong>Intro</strong><br />
Because we make use of the \ character regular expressions are almost always defined<br />
using @ʺ.<br />
Simple Patterns<br />
Regex re = new Regex(@"^B.*land");<br />
StreamReader sr = new StreamReader(@"..\..\ciaTabbed.txt");<br />
while (sr.Peek()>0)<br />
{<br />
string s = sr.ReadLine();<br />
if (re.Match(s).Success)<br />
Console.WriteLine(s);<br />
}<br />
The above section of code searches for strings that start with B and include ʺlandʺ<br />
Matches for ^B.*land<br />
Baker Island Oceania 1.4 0<br />
Bouvet Island Antarctic Region 58.5 0<br />
British Virgin Islands Central America and the Caribbean 150 19615 287000000<br />
5.11.1 Extracting substrings using Regular Expressions<br />
We can include brackets in our patterns and obtain the contents of these.<br />
Agilent .NET Course: Module 5, page 9