crazyfool
crazyfool

Reputation: 1463

Java Regex to replace string surrounded by non alphanumeric characters

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?

Upvotes: 1

Views: 2379

Answers (2)

Mark Peters
Mark Peters

Reputation: 81174

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

Upvotes: 4

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

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!

Upvotes: 2

Related Questions