Reputation: 26602
I thought it would be neat to parse IRC messages with a regular expression. I got as far as this:
(?::(?<Prefix>[^ ]+) +)?(?<Command>[^ :]+)(?<middle>(?: +[^ :]+)*)(?<coda> +:(?<trailing>.*)?)?
Then I use this with the following .NET code to get the salient elements of the message:
Prefix = matches.Groups["Prefix"].Value;
Command = matches.Groups["Command"].Value;
var parameters = new List<string>();
parameters.AddRange(matches.Groups["middle"].Value
.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries));
parameters.Add(matches.Groups["trailing"].Value);
Parameters = parameters.ToArray();
But I don't like that I have to split it separately in code. Is there a way that I can obtain an array of matches from the middle
group?
Upvotes: 1
Views: 1497
Reputation: 8459
You could use the Captures
property of a repeated group, although I wouldn't advice it.
First you would need to change your pattern to:
@"(?::(?<Prefix>[^ ]+) +)?(?<Command>[^ :]+)(?<middle>(?: +[^ :]+))*(?<coda> +:(?<trailing>.*)?)?"
Secondly, you would do:
parameters.AddRange(match.Groups["middle"].Captures.
OfType<Capture>().
Select(c => c.Value));
Upvotes: 4