REGEX: Getting information from a specific group which is surrounded by many optional groups

StackOverflow https://stackoverflow.com/questions/18037700

  •  23-06-2022
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top