4

I would like to get some values from a string with Regex. I'll proceed to explain:

  • There is a string: "Player #0 Agentep97 (12.34.56.78:1234) connected"
  • I'd like to get the #[NUMBER], Username ("Agentep97"), ([IP]:[Port]) values

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!

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

Lots of thanks! Worked perfectly! I would like to Upvote but I have no reputation, thanks anyway!!! :)
@HamZa: That's what I meant. The syntax is largely similar so it works pretty good for rapid prototyping. I didn't know about regexhero, so thanks for pointing that out :)
RegexBuddy is also very great!
Thanks! I'll also try it and tell you what
@ShadowHunter: if you don't have silverlight, you can use regexstorm.net
|
3

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:

[)]?[ :][#(]?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.