03.01.2015 Views

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The pattern @ʺ^(.*), Theʺ will match countries such as ʺBahamas, Theʺ. We can extract<br />

the contents of the brackets by looking at structure Match or MatchCollection.<br />

5.11.2 Match<br />

Commonly we are only interested in one <strong>set</strong> of matches.<br />

If this is the case we can use the Match object. We can get<br />

Extracting substrings<br />

Regex populationPattern = new Regex(@"Population: (\S*)");<br />

while (sr.Peek()>0)<br />

{<br />

string s = sr.ReadLine();<br />

Match m = populationPattern.Match(s);<br />

if (m.Success)<br />

{<br />

MessageBox.Show(m.Groups[1].Value);<br />

}<br />

}<br />

duction <strong>to</strong> .NET<br />

<strong>Intro</strong><br />

5.11.3 MatchCollection<br />

The match collection contains a list of lists. Commonly there is only one item in the<br />

list. This item consists of the whole matching string followed by each of the brackets<br />

in order.<br />

Extracting substrings<br />

Regex re = new Regex(@"^(.*), (The)\t");<br />

StreamReader sr = new StreamReader(@"..\..\ciaTabbed.txt");<br />

while (sr.Peek()>0)<br />

{<br />

string s = sr.ReadLine();<br />

MatchCollection m = re.Matches(s);<br />

if (m.Count>0)<br />

{<br />

Console.WriteLine(s);<br />

Console.WriteLine("item 0,0:" + m[0].Groups[0]);<br />

Console.WriteLine("item 0,1:" + m[0].Groups[1]);<br />

Console.WriteLine("item 0,2:" + m[0].Groups[2]);<br />

}<br />

}<br />

Output extracting substrings<br />

Bahamas, The Central America and the Caribbean 13940 294982 5580000000<br />

item 0,0:Bahamas, The<br />

item 0,1:Bahamas<br />

item 0,2:The<br />

Gambia, The Africa 11300 1367124 1400000000<br />

item 0,0:Gambia, The<br />

item 0,1:Gambia<br />

item 0,2:The<br />

Agilent .NET Course: Module 5, page<br />

10

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!