首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java regex中匹配特定分隔符内的组

如何在java regex中匹配特定分隔符内的组
EN

Stack Overflow用户
提问于 2021-03-16 16:17:06
回答 1查看 27关注 0票数 0

考虑一个字符串:

代码语言:javascript
复制
<! Women's boxing is yet to be recognized as an Olympic support,----. If that happens the dream of most of the tough girls may come true. !> <!  dream of most of the tough girls may come true. !> <! Women's boxing is yet to be recognized as an Olympic support. !>

在上面的字符串中,我使用了<!和!>作为指定段落边界的分隔符,从字符串中可以明显看出,我在分隔符中包含了3+1组封闭语句。

我用来捕获组的正则表达式是

代码语言:javascript
复制
<!([^<!>].+)!>

它匹配的组是:

代码语言:javascript
复制
Group 1: <! Women's boxing is yet to be recognized as an Olympic support,----. If that happens the dream of most of the tough girls may come true. !> <! dream of most of the tough girls may come true. !> <! Women's boxing is yet to be recognized as an Olympic support. !>

Group 2: Women's boxing is yet to be recognized as an Olympic support,----. If that happens the dream of most of the tough girls may come true. !> <! dream of most of the tough girls may come true. !> <! Women's boxing is yet to be recognized as an Olympic support. 

我假设匹配包括三个内部组,但它匹配它只包括外部组作为输出。这是我所期望的

代码语言:javascript
复制
//other groups

Women's boxing is yet to be recognized as an Olympic support,----. If that happens the dream of most of the tough girls may come true.

dream of most of the tough girls may come true.

Women's boxing is yet to be recognized as an Olympic support.
EN

回答 1

Stack Overflow用户

发布于 2021-03-17 00:56:23

模式<!([^<!>].+)!>从与除<!>之外的任何字符匹配的组中的第一个字符开始。然后,.+将一直匹配到行的末尾,并回溯到第一次遇到!>

如果您不想捕获空格字符,可以匹配开头和结尾的空格字符,并使用非空格字符\S启动捕获组,而不仅仅是匹配空格字符。

然后使用延迟匹配,直到第一次出现!>

代码语言:javascript
复制
<!\s*(\S.*?)\s*!>

Regex demo

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66651324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档