【问题标题】:Regex replace but exclude everything inside <title> </title>正则表达式替换但排除 <title> </title> 内的所有内容
【发布时间】:2021-01-02 20:48:06
【问题描述】:

我想使用 Regex 查找 HTML 代码中的所有单词匹配,然后用链接替换它们,但我需要排除标题标签内的所有内容。

HTML:

<p> 
    This is Apple text.
</p>

<title>
    Apple is good for your health.
</title>


我要替换:

Apple

到:

<a href="/search/apple">Apple</a>


现在我正在替换:

/>([^<]*)?(Apple)([^>]*)?</

替换为:

>$1<a href="/search/apple">$2</a>$3<

但结果是

<p> 
    This is <a href="/search/apple">Apple</a> text.
</p>

<title>
    <a href="/search/apple">Apple</a> is good for your health.
</title>

我需要排除标题标签内的 Apple 一词被替换。
就像这样:

<p> 
    This is <a href="/search/apple">Apple</a> text.
</p>

<title>
    Apple is good for your health.
</title>

请帮忙。

对不起我的英语不好。谢谢你的帮助。
我真的很感激。

【问题讨论】:

  • 我想你也不想在&lt;!-- Here is an Apple --&gt;&lt;input value="Apple"&gt;&lt;script&gt;class Apple {}&lt;/script&gt;Applepie&lt;a href="http://example.org/Apple"&gt;、@987654333 中替换 Apple @,...等,...等。用正则表达式解析 HTML 是一场灾难。
  • 我没有遇到过那种麻烦。嗯……但现在看起来不错????

标签: regex


【解决方案1】:

如果您在正则表达式中添加负前瞻,则可以排除标题标签:

>([^<]*)?(Apple)([^>]*)?<(?!\/title)

查看示例:https://regex101.com/r/svErYD/1/

【讨论】:

  • 有效。谢谢你让我的生活更轻松??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-13
  • 2014-08-10
  • 1970-01-01
相关资源
最近更新 更多