Tim
Tim

Reputation: 2050

Java: regex replace string

Consider the following String:

s = "Ralph was walking down the street, he saw Mary and fell in love with her. Judy loves her hair."

I've got an ArrayList<ArrayList<String>> anaphora with the correct matches and sentence number and ArrayList<String> sentences with the sentences from s. Both look like this:

anaphora.get(0) = [0, Ralph, he]
anaphora.get(1) = [0, Mary, her]
anaphora.get(2) = [0, the street]
anaphora.get(3) = [1, Judy, her]
anaphora.get(4) = [1, her hair]

sentences.get(0) = Ralph was walking down the street, he saw Mary and fell in love with her.
sentences.get(1) = Judy loves her hair.

Now the problem arises when trying to replace the substrings.

sentence = sentences.get(0);
if (anaphora.get(0).size()>2){
    example1 = sentence.replaceAll("[^a-zA-Z]"+anaphora.get(0).get(i)+"[^a-zA-Z]", anaphora.get(0).get(1));
    example2 = sentence.replaceAll(anaphora.get(0).get(i), anaphora.get(0).get(1));
}

Output will be:

example1 = Ralph was walking down the street,Ralphsaw Mary and fell in love with her.
example2 = Ralph was walking down tRalph street, Ralph saw Mary and fell in love with Ralphr.

The expected output would be in such a way that 'he' gets replaced with 'Ralph':

Ralph was walking down the street, Ralph saw Mary and fell in love with her.

Question How can I fix my regex replace so that ONLY the correct 'he' gets replaced?

Upvotes: 0

Views: 187

Answers (2)

duffy356
duffy356

Reputation: 3718

you need to be careful of the blanks. so your regex should only do the replacement, if the replaced string is a word.

Upvotes: 0

assylias
assylias

Reputation: 328598

As commented above, you can use a word boundary, for example:

String s = "Ralph was walking down the street, he saw Mary and fell in love with her.";
System.out.println(s.replaceAll("\\bhe\\b", "Ralph"));

prints:

Ralph was walking down the street, Ralph saw Mary and fell in love with her.

Upvotes: 1

Related Questions