What is the Java equivalent to this preg_replace?

后端 未结 3 1687
谎友^
谎友^ 2021-02-09 15:54
wordword word\";
    $str = preg_replace(\"/word(?!([^<]+)?>)/i\",\"repl\",$str);
    echo $str;         


        
相关标签:
3条回答
  • 2021-02-09 16:03

    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.

    0 讨论(0)
  • 2021-02-09 16:09

    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");
    
    0 讨论(0)
  • 2021-02-09 16:11

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

    0 讨论(0)
提交回复
热议问题