问题
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