0

Trying to wrap my head around Regex capturing groups and having a little trouble.

I have some strings for which I want to capture groups for:

@msg=hello;name=test 1 // Groups: msg = hello, name = test, rest = 1 
@msg=hi 2 // Groups: msg = hello, name = null, rest = 2
@name=tt 3 // Groups: msg = null, name = tt, rest = 3

I have the following regex:

msg=(?P<msg>[^;]+)?.*name=(?P<name>[^;]+)?\s(?P<rest>.*)

Which works fine for the first row, but not the second or third. Any idea how I can make it work for them too? I tried putting some ()? around the capturing groups to no avail:

// Below gets me weird results
(msg=(?P<msg>[^;]+)?)?.*(name=(?P<name>[^;]+)?)?\s((?P<rest>.*))?

Thanks.

1
  • There's some great Regex testers out there that should be able to help you. Play around with regexr.com until you find what you're looking for, you can learn a lot while doing it :) Commented Sep 14, 2015 at 1:38

1 Answer 1

1

You should use a more strict token rather than negation, using optional non-capturing groups:

@(?:msg=(?<msg>\w+);?)?(?:name=(?<name>\w+))?\s*(?<rest>.*)

Regex Demo

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

2 Comments

I'm very firm with Regex but I didn't see the construct (?P< for named groups in C# before. What's the difference between (?P<xxx> and (?<xxx>? Msdn doesn't know this pattern. Btw: This pattern doesn't work in C#. Are we really talking about C#?
Sorry, it was intended to be reduced before but it saved the post with the original named group.

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.