0

Suppose I have a regex expression that matches a string like this:

(A)(B)?(C)(D)?(E)(F)?

where the groups B, D, and F are optional.

How can I get just group E? I ask this because, I don't think I can just call M.group(5) because if my matcher (M) didn't find groups B and D, then group E is actually group 3 and not group 5.

I did have an idea though.If I did something like:

((A)(B)?(C)(D)?)(E)(F)?

where A,B,C, and D are all group 1, can I call group 2 to get E?

Thank you.

Rohit Jain
  • 195,192
  • 43
  • 369
  • 489

1 Answers1

2

Actually, you can just call M.group(5) because the optional capture groups will match null, per this fiddle.

Peter Alfvin
  • 26,897
  • 7
  • 60
  • 98
  • Oh, I tried it and it work! I'm just learning regex expressions so I didn't know that -- thank you so much! – user2649427 Aug 03 '13 at 22:24
  • Welcome to Stack Overflow! If my answer helped to solve your problem, please consider marking it as [accepted](http://stackoverflow.com/faq#howtoask). That's the customary way of indicating that your question is "resolved" and thanking the person who helped you. – Peter Alfvin Aug 03 '13 at 22:43