contraflow contraflow - 1 month ago 11
C# Question

Regex parsing using named capture groups

Can anyone provide an example of how the below string can be parsed using named capture groups?


UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:


into the following:

Date: 20160930

*Home Team: HomeTeam

Home Score: 17

*Away Team: AwayTeam

Away Score: 26

(*note: removal of space)


UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:

Answer

Simple regex, like this

var regex = 
 new Regex("UID:([0-9]+)T\\d+Z([a-zA-Z ]+) ([0-9]+) - ([0-9]+) ([a-zA-Z ]+)END:");
var match = regex.Match("UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:");
foreach(Group group in match.Groups)
    Console.WriteLine(group.Value);

will produce following out:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:
20160930
Home Team
7
26
Away Team

UPD Using named groups

var regex = 
new Regex("UID:(?<date>[0-9]+)T\\d+Z(?<home_team>[a-zA-Z ]+) (?<home_score>[0-9]+) - (?<away_score>[0-9]+) (?<away_team>[a-zA-Z ]+)END:");
var match = regex.Match("UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:");

foreach(Group group in match.Groups)
    Console.WriteLine(group.Value);

Console.WriteLine("-----------------------");

Console.WriteLine(match.Groups["date"].Value);
Console.WriteLine(match.Groups["home_team"].Value);
Console.WriteLine(match.Groups["home_score"].Value);
Console.WriteLine(match.Groups["away_score"].Value);
Console.WriteLine(match.Groups["away_team"].Value);

Out:

UID:20160930T183500ZHome Team 17 - 26 Away TeamEND:
20160930
Home Team
17
26
Away Team
-----------------------
20160930
Home Team
17
26
Away Team
Comments