Reputation: 290
I would like to get some values from a string with Regex. I'll proceed to explain:
I already tried with var match = Regex.Match(input, @"Player #(?<player_id>[0-9]{1,3})\s(?<user>.+)\s\((<ip1>\d{1,3})\.(<ip2>\d{1,3})\.(<ip3>\d{1,3})\.(<ip4>\d{1,3})\:(<port>\d{1,5}$)\) connected\W\D\S", RegexOptions.IgnoreCase);
but I the Match didn't succeed so I couldn't get player_id.Value and such.
How would you do it? Is "var match" not correct or anything?
Thanks in advance!
Upvotes: 4
Views: 136
Reputation: 89557
You can use this pattern:
Player #(?<number>[0-9]+) (?<username>\S+) \((?<ip>(?>[0-9]{1,3}\.){3}[0-9]{1,3}):(?<port>[0-9]+)\)
I don't think you need to catch all separate numbers of the IP address.
An other way is to use the split method with this pattern:
[)]?[ :][#(]?
Upvotes: 3
Reputation: 56769
Regular expressions can be frustrating for this very reason: it's often an all or nothing with no clear explanation why it isn't working. What I would suggest is how I went about reviewing your regular expression. I added in one character/group at a time until it stopped matching (using the very helpful and mostly .NET-compatible tool Rubular), and then looked at what broke the regular expression. In this case, it looks like you just forgot the ?
in the named groups ip1
, ip2
, ip3
, ip4
, and port
:
Player #(?<player_id>[0-9]{1,3})\s(?<user>.+)\s\(
(?<ip1>\d{1,3})\.(?<ip2>\d{1,3})\.(?<ip3>\d{1,3})\.(?<ip4>\d{1,3})\:(?<port>\d{1,5}$)\) connected\W\D\S
^ ^ ^ ^ ^
Demo: http://www.rubular.com/r/J8dEEE3HnC
Upvotes: 3