与此 preg_replace 等效的 Java 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3304925/
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
What is the Java equivalent to this preg_replace?
提问by celsowm
<?php
$str = "word <a href=\"word\">word</word>word word";
$str = preg_replace("/word(?!([^<]+)?>)/i","repl",$str);
echo $str;
# repl <word word="word">repl</word>
?>
source: http://pureform.wordpress.com/2008/01/04/matching-a-word-characters-outside-of-html-tags/
来源:http: //pureform.wordpress.com/2008/01/04/matching-a-word-characters-outside-of-html-tags/
Unfortunality my project needs a semantic libs avaliable only for Java...
不幸的是,我的项目需要一个仅适用于 Java 的语义库...
// Thanks Celso
// 谢谢塞尔索
回答by kolrie
Use the String.replaceAll() method:
使用 String.replaceAll() 方法:
class Test {
public static void main(String[] args) {
String str = "word <a href=\"word\">word</word>word word";
str = str.replaceAll("word(?!([^<]+)?>)", "repl");
System.out.println(str);
}
}
Hope this helps.
希望这可以帮助。
回答by Alan Moore
To translate that regex for use in Java, all you have to do is get rid of the /delimiters and change the trailing ito an inline modifier, (?i). But it's not a very good regex; I would use this instead:
要将该正则表达式转换为在 Java 中使用,您所要做的就是去掉/分隔符并将尾随更改为i内联修饰符(?i). 但这不是一个很好的正则表达式;我会用这个代替:
(?i)word(?![^<>]++>)
According to RegexBuddy's Debug feature, when it tries to match the wordin <a href="word">, the original regex requires 23 steps to reject it, while this one takes only seven steps. The actual Java code is
根据 RegexBuddy 的 Debug 功能,当它尝试匹配wordin 时<a href="word">,原始正则表达式需要 23 步才能拒绝它,而这个只需 7 步。实际的Java代码是
str = str.replaceAll("(?i)word(?![^<>]++>)", "repl");
回答by Zak
Before providing a further answer, are you trying to parse an html document? If so, don't use regexes, use an html parser.
在提供进一步的答案之前,您是否尝试解析 html 文档?如果是这样,不要使用正则表达式,使用 html 解析器。

