Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top