【问题标题】:How to match groups inside a specific delimiter in java regex如何在java正则表达式中匹配特定分隔符内的组
【发布时间】:2021-03-16 08:17:05
【问题描述】:

考虑一个字符串:

<! 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 组封闭语句。

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

<!([^<!>].+)!>

它匹配的组是:

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. 

我认为匹配包含三个内部组,但它匹配它只包含外部组作为输出。 这是我的预期

//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.

【问题讨论】:

标签: regex regex-group regex-greedy


【解决方案1】:

模式&lt;!([^&lt;!&gt;].+)!&gt; 开始匹配除&lt; !&gt; 之外的任何字符的组中的第一个字符。然后.+会匹配到行尾,并且会回溯到第一次遇到!&gt;

如果您不想捕获空白字符,您可以匹配开头和结尾的字符,并以非空白字符 \S 开始捕获组,以不仅匹配空白字符。

然后使用惰性匹配直到第一次出现!&gt;

<!\s*(\S.*?)\s*!>

Regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多