What is the Java equivalent to this preg_replace?

若如初见. 提交于 2019-12-04 12:13:43

问题


<?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/

Unfortunality my project needs a semantic libs avaliable only for Java...

// Thanks Celso


回答1:


Use the String.replaceAll() method:

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.




回答2:


To translate that regex for use in Java, all you have to do is get rid of the / delimiters and change the trailing i to an inline modifier, (?i). But it's not a very good regex; I would use this instead:

(?i)word(?![^<>]++>)

According to RegexBuddy's Debug feature, when it tries to match the word in <a href="word">, the original regex requires 23 steps to reject it, while this one takes only seven steps. The actual Java code is

str = str.replaceAll("(?i)word(?![^<>]++>)", "repl");



回答3:


Before providing a further answer, are you trying to parse an html document? If so, don't use regexes, use an html parser.



来源:https://stackoverflow.com/questions/3304925/what-is-the-java-equivalent-to-this-preg-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!