正则表达式替换&,但仅在链接内

时间:2013-11-20 13:05:04

标签: java regex

我正在尝试编写一个正则表达式,用双星**替换&符号(&),但仅限于包含在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;",但是在链接中包含它时遇到问题。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您可以使用:

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);
相关问题