gpt4 book ai didi

java - 使 .replaceFirst() 在特定字符之后开始

转载 作者:行者123 更新时间:2023-11-30 08:19:10 28 4
gpt4 key购买 nike

有什么方法可以让 .replaceFirst() 开始仅替换特定字符串之后的 a 吗?例如我知道正则表达式不能很好地处理 html,并且我的 html 文本由 1 个 h2 标题和一个段落组成。现在,我使用软件替换的关键字可以完美工作,但有时标题中的关键字也会被替换。有什么方法可以让java知道在第一个之后开始raplacing

</h2>

字符串?

最佳答案

如果您想要一个正则表达式来解决(这样使用 replaceFirst()replaceAll() 就没有区别),我可以建议使用捕获组:

(?s)(<\/h2.+)\b(keyword)\b(?=.*<\/h2>.*$)

 String regex = "(?s)(<\\/h2.+)\\b(keyword)\\b(?=.*<\\/h2>.*$)";

将“关键字”替换为您的单词,并使用“$1[replacement_keyword]”作为替换字符串。

这是一个code example :

String input = "<title>Replacing keywords with keyword</title>\n"+
"<body>\n"+
"<h2>Titles</h2>\n"+
"<p>Par with keywords and keyword</p>\n"+
"<h2>Titles</h2>\n"+
"<p>Par with keywords and keyword</p>\n"+
"</body>";
String regex = "(?s)(<\\/h2.+)\\b(keyword)\\b(?=.*<\\/h2>.*$)";
String keytoreplacewith = "NEW_COOL_KEYWORD";
String output = input.replaceFirst(regex, "$1"+keytoreplacewith);
System.out.println(output);

输出:

<title>Replacing keywords with keyword</title>
<body>
<h2>Titles</h2>
<p>Par with keywords and NEW_COOL_KEYWORD</p>
<h2>Titles</h2>
<p>Par with keywords and keyword</p>
</body>

关于java - 使 .replaceFirst() 在特定字符之后开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207033/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com