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

来源: http: //pureform.wordpress.com/2008/01/04/matching-a-word-characters-outside-of-html-tags/

不幸的是,我的项目需要一个仅适用于 Java 的语义库......

// 谢谢塞尔索

4

3 回答 3

13

使用 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);
  }
}

希望这可以帮助。

于 2010-07-22T03:13:06.677 回答
3

要翻译该正则表达式以在 Java 中使用,您所要做的就是去掉/分隔符并将尾随更改i为内联修饰符(?i). 但这不是一个很好的正则表达式;我会改用这个:

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

根据 RegexBuddy 的 Debug 特性,当它试图匹配wordin<a href="word">时,原来的 regex 需要 23 步来拒绝它,而这个只需要 7 步。实际的Java代码是

str = str.replaceAll("(?i)word(?![^<>]++>)", "repl");
于 2010-07-22T08:01:27.963 回答
1

在提供进一步的答案之前,您是否尝试解析 html 文档?如果是这样,不要使用正则表达式,使用 html 解析器。

于 2010-07-22T00:29:55.383 回答