【问题标题】:Regex with negative lookahead and dot matches newline modifier (/s)带有负前瞻和点的正则表达式匹配换行符 (/s)
【发布时间】:2019-05-30 22:31:41
【问题描述】:

我有一个 PHP 脚本,我需要匹配特定字符串的最后一次出现。

假设我有以下场景:

1

<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>

2

Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>

3

Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este 
texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>

4

Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este <font></font>
texto não substitui o publicado no DOU de  28.9.2006.</font>
</p>

5

Este texto abc def
<p class="TPTexto" style="text-autospace: none; ">
<font face="Arial" size="2" color="#FF0000">Este            texto não substitui     o     publicado no DOU de  28.9.2006.</font>
</p>

我想在所有情况下都匹配Este texto não substitui o publicado,在两者之间接受一些偶尔的垃圾,比如Este &lt;font&gt;&lt;/font&gt;\ntexto não substitui o publicado

所以我使用了以下正则表达式:
/Este(?:.(?!Este))+?texto.+?n.+?o.+?substitui.+?o.+?publicado/uis

标志:
u 接受 unicode 字符
i 接受不敏感的内容
s 使点 (.) 匹配换行符(所以我的否定前瞻有效)

这样我匹配最后一个 Este 和下面的文本,我想要的,对吧?没有! s 修饰符杀死了它。
(我正在使用 this PHP tool 来测试它)

我不知道为什么 s 修饰符在这种情况下会杀死它。任何帮助将不胜感激。


我在这个项目中使用 PHP 的 preg_match_all

编辑

注意到不清楚:我需要第二个 Este texto... 而不是第一个。

【问题讨论】:

  • 它看起来可以在 regex101 上正常工作,regex101.com/r/VHb2gm/1。从那里生成的 PHP 似乎也可以工作,3v4l.org/ZR1fZ。您能否澄清一下这个问题,它是否特定于那个工具
  • 为什么投反对票?它不适用于 regex101,在您的示例中,我没有得到最后一个“Este texto”,而是第一个“Este texto”,
  • @user3783243 不知道你为什么投了反对票,也投了反对票。不确定你是否仔细阅读了这个问题。请删除反对票并关闭投票。
  • 使用\A.*\KEste.+?texto.+?n.+?o.+?substitui.+?o.+?publicado。在此处查看现场演示 regex101.com/r/nsMRLj/1
  • @revo 太棒了!似乎正在工作。我和一位同事一起花了大约 1 小时来解决这个问题,但我们没有成功。不确定\K 做了什么...请添加为答案并澄清它的作用,我很乐意接受正确的答案。

标签: php regex regex-lookarounds regex-negation regex-group


【解决方案1】:

你的正则表达式没问题。你可以在你的正则表达式前面加上这个:

\A.*\K
  • \A 断言输入字符串的开头
  • .* 立即匹配整个输入字符串,然后尝试回溯以匹配下一个模式 Este
  • \K 将输出重置到该点,以便您只看到所需的字符串

我删除了前瞻,使您的正则表达式更简单一些。综上所述,我们有这个:

\A.*\KEste.+?texto.+?n.+?o.+?substitui.+?o.+?publicado

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2021-10-11
    • 2015-08-22
    相关资源
    最近更新 更多