替代替代

时间:2019-09-03 12:11:23

标签: java regex

我们如何替代替代品?这是一个示例说明:

<h1>test test</h1>
<h2>sometext</h2>

我想替换为:

<h1 id="test-test">test test</h1>
<h2 id="sometext">sometext</h2>

请注意,id="test-test"带有短划线,由空格字符和<h1>test test</h1>代替,这就是为什么问题被命名为“替换替代”

我知道,使用多个<(h[1-6])>(.*)<\\/\\1>这样的正则表达式然后找到h1 id="..."并替换将可以解决问题,但是我想在单个正则表达式中做到这一点。有可能吗?

1 个答案:

答案 0 :(得分:2)

Pattern.compile("<h1>(.*?)</h1>").matcher(s).replaceAll(mr ->
    "<h1 id=" + mr.group(1).replace(' ', '-') + "> " + ...);

Pattern.compile("<h1>(.*?)</h1>").matcher(s).replaceAll(mr -> {
    return "<h1 id=" + mr.group(1).replace(' ', '-') + "> " + ...;
});
  • 也就是说,使用replaceAll的lambda版本(自Java 9开始)。
  • 替换最短序列.*?,使...<h1>...</h1>...<h1>...</h1>...没问题。
  • mrMatchResult