Match contents surrounded by optional group in Java regex

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. Example matches: * `foo/` * `~foo~/` * `~foo/~/` * `~foo~~/` * `~foo/bar~/` and some that wouldn't match: * `foo~//` * `~foo~/bar~/` * `~foo/` * `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]( 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前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准