I'm having trouble wrapping my head around how a particular Java regex should be written. The regex will be used in a sequence, and will match sections ending with `/`.
The problem is that using a simple split won't work because the text before the `/` can optionally be surrounded by `~`. If it is, then the text inside can match anything - including `/` and `~`. The key here is the ending `~/`, which is the only way to escape this 'anything goes' sequence if it begins with `~`.
Because the regex pattern will be used in a sequence (i.e. `(xxx)+`), I can't use `^` or `$` for non-greedy matching.
and some that wouldn't match:
* `foo~/` (see edit 2)
Is there any way to do this without being redundant with my regexes? What would be the best way to think about matching this? Java doesn't have a conditional modifier (`?`) so that complicated things in my head a bit more.
**EDIT**: After working on this in the meantime, the regex `((?:\~())?)(((?!((?!\2)/|\~/)).)+)\1/` [gets close](http://fiddle.re/wtfna) but #6 doesn't match.
**EDIT 2**: After Steve pointed out that there is ambiguity, it became clear #6 shouldn't match. And why a regex and not a utility method which will return whatever is needed?
以上就是Match contents surrounded by optional group in Java regex的详细内容，更多请关注web前端其它相关文章！