【问题标题】:How can I match the first instance of a pattern?如何匹配模式的第一个实例?
【发布时间】:2014-04-27 23:07:17
【问题描述】:

我有以下正则表达式和输入。

http://regex101.com/r/rY5xD2:

^(.+)\byo\b.*?(cut me:)

如何只匹配模式匹配的第一个实例?

-- 所需的组匹配(我保留的文本)--

Hi

yo keep this here

Keep this here

【问题讨论】:

  • 对不起,我不明白你不想从那段中得到第一句话或第一行。

标签: java regex


【解决方案1】:

你可以使用:

^(.+?)\byo\b(?:(?!cut me:|yo).)*cut me:

在线演示:http://regex101.com/r/sB3kK5

【讨论】:

    【解决方案2】:

    你可以试试^(((?!cut me:).)+)\byo\b.*?(cut me:)

    建议不接受以cut me: 开头的字符。但要小心,因为这种方法对于更长的字符串可能非常昂贵,然后"cut me:" 因为回溯。

    DEMO

    【讨论】:

    • 非常酷,感谢您的回复!关于回溯的观点。
    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2021-04-10
    • 2018-11-02
    • 2012-11-12
    • 1970-01-01
    • 2015-08-08
    • 2020-02-09
    • 2020-08-04
    相关资源
    最近更新 更多