8

I have strings that are in the format:

X=Foo, Y=Bar, Z=Qux

However, sometimes only the X=...Y=... parts are there, not the Z=... part, e.g:

X=Foo, Y=Bar

And also can capture commas within values, like:

X=Foo, bar, Y=Bar, Z=Qux

How can I write a regex to capture Foo, Bar, and Qux (just placeholders for this example) if present?

I've come up with this so far:

X=(.*), Y=(.*)           # Works when Z is not present
X=(.*), Y=(.*), Z=(.*)   # Works when Z is present

But I'm having trouble writing a single regex to match both cases. I also tried something like this:

X=(.*), Y=(.*)(, Z=(.*))?

I thought that by grouping the ,Z=(.*) in its own group followed by a ? it would treat the whole group as optional, but it still seems to group the Z= as part of the captured part from the Y=.

0

1 Answer 1

10

You were very close - you're capturing it, but in group 4, due to the new group you introduced to make the last part optional.

Change the introduced group to a non-capturing group:

X=(.*?), Y=(.*?)(?:, Z=(.*))?$

I also fixed your capture to reluctant (instead of .*, which is greedy and consumes the entire rest of input).

See live demo.

4
  • I don't want to use \w because the values may contain other characters, including commas. Are you able to revise your answer?
    – Joseph
    Jan 12, 2016 at 0:51
  • sure. is a comma-then-space a suitable separator then?
    – Bohemian
    Jan 12, 2016 at 0:52
  • 1
    Hmm, I can't be certain right now. Is it possible to write a regex that could capture, for example, both: X=foo, bar, Y=baz, Z=qux (catpure foo, bar, baz, and qux) and X=foo, Y=bar (capture foo and bar) ?
    – Joseph
    Jan 12, 2016 at 0:55
  • @Joseph I have fixed the regex to match "anything"
    – Bohemian
    Jan 12, 2016 at 1:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.