java 替换标签内的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11138425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:56:51  来源:igfitidea点击:

Replace string inside tags?

javaregex

提问by membersound

I want to replace a content inside some tags, eg:

我想替换一些标签内的内容,例如:

<p>this it to be replaced</p>

I could extract the content between with groups like this, but can i actually replace the group?

我可以像这样提取组之间的内容,但我实际上可以替换组吗?

str = str.replaceAll("<p>([^<]*)</p>", "replacement");

采纳答案by Bohemian

Change the regex to this:

将正则表达式更改为:

(?<=<p>).*?(?=</p>)

ie

IE

str = str.replaceAll("(?<=<p>).*?(?=</p>)", "replacement");

This uses a "look behind" and a "look ahead" to assert, but not capture, input before/after the matching (non-greedy) regex

这使用“后视”和“前视”来断言但不捕获匹配(非贪婪)正则表达式之前/之后的输入

Just in case anyone is wondering, this answer is different to dacwe's: His uses unnecessary brackets. This answer is the more elegant :)

以防万一有人想知道,这个答案与 dacwe 的不同:他使用了不必要的括号。这个答案更优雅:)

回答by dacwe

You can use lookaround(positive lookahead and lookbehind) for this:

您可以为此使用环视(正向前瞻和后视):

Change the regex to: "(?<=<p>)(.*?)(?=</p>)"and you will be fine.

将正则表达式更改为:"(?<=<p>)(.*?)(?=</p>)"你会没事的。



Example:

例子:

String str = "<p>this it to be replaced</p>";
System.out.println(str.replaceAll("(?<=<p>)(.*?)(?=</p>)", "replacement"));

Output:

输出:

<p>replacement</p>


Note however that if you are parsing HTML you should be using some kind of a HTML parser, often regular expressions is not good enough...

但是请注意,如果您正在解析 HTML,您应该使用某种 HTML 解析器,通常正则表达式不够好......