2

In my application I'm giving dictionary word suggestions and replacing the selected word with the suggested word using .replaceAll(). However that is replacing every sub string in the entire string

for example in this String,

String sentence = "od and not odds as a sample sam. but not odinary";

If I suggest the first word as odd .replaceAll() will replace every occurrence of od with odd hence affecting the fourth word to oddds and changing the sentence to

sentence.replaceAll("od", "odd");



//sentence String becomes
sentence ="odd and not oddds as a sample sam. but not oddinary"

Replacing the od to odd has affected all the other words which have the od characters in them.

Can any one help me with a better aproach?

IsaacK
  • 1,178
  • 1
  • 19
  • 49

3 Answers3

4

Use regex. For you example "\bod\b" will just match od as a whole word. \b is a word boundary, meaning either the start or the end of a word (whether it ends with a dot or a whitespace or anything else).

The replaceAll method can already take in a regex, but if you need more power you can look at the Matcher class.

String REPLACE_WORD = "od"
sentence.replaceAll("\\b" + REPLACE_WORD + "\\b", "odd");

will give you the correct answer. The \ tells java that you want to write \ instead of \b (it first parses the string, and than parses that string as regex).

Astrogat
  • 1,617
  • 12
  • 24
0

Use the regular expression in the replaceAll() method:

\bod\b

This will filter out occurrences of the od inside any other word. Of course when you use it in Java method, you need to escape the \

So

replaceAll("\\bod\\b", "odd");

should do it.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Samrat Dutta
  • 1,727
  • 1
  • 11
  • 23
0

As mentioned, you can use a Matcher from Java.util.regex.* which has a lot of useful functionality.

String text = "I detect quite an od odour.";
String searchTerm = "\\bod\\b";

Pattern pattern = Pattern.compile(searchTerm);
Matcher matcher = pattern.matcher(text);

text = matcher.replaceAll("odd");

System.out.println(text);

The output would be:

I detect quite an odd odour.