Java Regex to replace string surrounded by non alphanumeric characters

雨燕双飞 提交于 2020-01-05 12:13:12

问题


I need a way to replace words in sentences so for example, "hi, something". I need to replace it with "hello, something". str.replaceAll("hi", "hello") gives me "hello, somethellong".

I've also tried str.replaceAll(".*\\W.*" + "hi" + ".*\\W.*", "hello"), which I saw on another solution on here however that doesn't seem to work either.

What's the best way to achieve this so I only replace words not surrounded by other alphanumeric characters?


回答1:


Word boundaries should serve you well in this case (and IMO are the better solution). A more general method is to use negative lookahead and lookbehind:

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

This searches for occurrences "ab" that are not preceded or followed by another word character. You can swap out "\w" for any regex (well, with practical limitations as regex engines don't allow unbounded lookaround).




回答2:


Use \\b for word boundaries:

String regex = "\\bhi\\b";

e.g.,

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

  System.out.println(newString);

If you're going to be doing any amount of regular expressions, make this Regular Expressions Tutorial your new best friend. I can't recommend it too highly!



来源:https://stackoverflow.com/questions/10365360/java-regex-to-replace-string-surrounded-by-non-alphanumeric-characters

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