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?
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:
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).