这个preg_replace的Java等价物是什么?
<?php $str = "word wordword word"; $str = preg_replace("/word(?!([^)/i","repl",$str); echo $str; # repl repl ?>
来源: http : //pureform.wordpress.com/2008/01/04/matching-a-word-characters-outside-of-html-tags/
不幸的是,我的项目需要一个仅适用于Java的语义库…
//谢谢Celso
使用String.replaceAll()方法:
class Test { public static void main(String[] args) { String str = "https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/wordhttps://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word"; str = str.replaceAll("https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word(?!([^<]+)?>)", "repl"); System.out.println(str); } }
希望这可以帮助。
要翻译该正则表达式以便在Java中使用,您所要做的就是去除/
分隔符并将尾随i
更改为内联修饰符(?i)
。 但它不是一个非常好的正则表达式; 我会改用它:
(?i)https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word(?![^<>]++>)
根据RegexBuddy的调试function,当它试图匹配中的
https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word
时,原始正则表达式需要23个步骤来拒绝它,而这个步骤只需要7个步骤。 实际的Java代码是
str = str.replaceAll("(?i)https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace/word(?![^<>]++>)", "repl");
在提供进一步的答案之前,您是否正在尝试解析html文档? 如果是这样,请不要使用正则表达式,使用html解析器。