0

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?

5
  • 1
    what are trying to do? Can you provide a CLEAR example? Commented Apr 17, 2013 at 10:10
  • 1
    What is expected output? Commented Apr 17, 2013 at 10:11
  • 2
    try with boundary \b pattern. Your pattern will be \\bhe\\b for matching exactly he. for more see :regular-expressions.info/wordboundaries.html Commented Apr 17, 2013 at 10:14
  • 1
    sentence.replaceAll(anaphora.get(0).get(i), anaphora.get(1)) replacement is ArrayList<String>? Commented Apr 17, 2013 at 10:14
  • I fixed my question, hopefully it's a bit more clear now. Commented Apr 17, 2013 at 10:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.