【问题标题】:regular expression to replace &, but only inside a link正则表达式替换 &,但仅在链接内
【发布时间】:2013-11-20 23:04:37
【问题描述】:

我正在尝试编写一个正则表达式,用双星 ** 替换 & 字符 (&),但仅当包含在 html HREF 属性(绝对或相对)中时。另外,我需要它来匹配完整的"&" 字符串

例如,下面的 HTML 块:

<p>Ben & Jerry is <a href="http://www.domain.com?a=1&b=2&amp;c=3">cool</a></p>
<p>Ben & Jerry is <a href="/index.htm?a=1&b=2&amp;c=3">cool</a></p>

会变成

<p>Ben & Jerry is <a href="http://www.domain.com?a=1**b=**c=3">cool</a></p>
<p>Ben & Jerry is <a href="/index.htm?a=1**b=2**c=3">cool</a></p>

我可以替换所有“&”和所有 "&amp;amp;"s,但在将其包含在链接中时遇到问题。

谁能帮忙?

【问题讨论】:

  • 是否必须使用正则表达式?使用 HTML 解析器可能会更好。
  • 我可以想象为
  • 恐怕它确实需要是一个正则表达式。这实际上将使用我们的内容管理系统的自定义语言,在一个无法使用 HTML 解析器的非常奇怪的设置中。我唯一可以使用的就是正则表达式。
  • &lt;a(.*)href=(.*)&amp;(.*)&gt;(.*)&lt;/a&gt; 将匹配
  • 这行不通 Maciej Dobrowolski。

标签: java regex


【解决方案1】:

你可以用这个:

String html = "<p>Ben & Jerry is <a href=\"http://www.domain.com?a=1&b=2&amp;c"
            + "=3\">cool</a></p>\n<p>Ben & Jerry is <a href=\"/index.htm?a=1&b"
            + "=2&amp;c=3\">cool</a></p>";
String pattern = "(?i)" + // case insensitive modifier
            "(" + // open the capturing group 1
                "(?:" + // open a non capturing group
                    "<a\\s[^>]*?\\bhref\\s*=\\s*[\"']?" + // content until the href attribute value
                  "|" + // OR
                    "\\G(?<!^)" + // contiguous to a precedent match
                ")" + // close the non capturing group
                "[^\\s\"'&>]++" + // value content that is not a &
            ")" + // close the capturing group 1
            "&(?:amp;)?"; // & with optional "amp;"
String res = html.replaceAll(pattern, "$1**");
System.out.println(res);

【讨论】:

  • 对不起,这里的回复有点晚,我已经离开了。这就像一个魅力,我非常感谢你的解释。谢谢你的一切
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多