Java Regex 用于替换由非字母数字字符包围的字符串



我需要一种方法来替换句子中的单词,例如"嗨,某事"。 我需要用"hello, something"替换它. str.replaceAll("hi", "hello")给了我"hello, somethellong".

我也尝试了str.replaceAll(".*\W.*" + "hi" + ".*\W.*", "hello"),我在这里的另一个解决方案上看到了,但是似乎也不起作用。

实现此目的的最佳方法是什么,以便我只替换未被其他字母数字字符包围的单词?

在这种情况下,

单词边界应该对您有用(IMO是更好的解决方案)。 更通用的方法是使用负前瞻和后视:

 String input = "ab, abc, cab";
 String output = input.replaceAll("(?<!\w)ab(?!\w)", "xx");
 System.out.println(output); //xx, abc, cab

这将搜索在另一个单词字符之前或后面没有出现"ab"的匹配项。 你可以用"\w"换成任何正则表达式(嗯,有实际限制,因为正则表达式引擎不允许无限的环顾)。

使用 \b 表示单词边界:

String regex = "\bhi\b";

例如,

  String text = "hi, something";
  String regex = "\bhi\b";
  String newString = text.replaceAll(regex, "hello");
  System.out.println(newString);

如果您要使用任意数量的正则表达式,请让本正则表达式教程成为您最好的新朋友。我不能推荐它太高!

最新更新