Рассмотрим следующую строку:Java: регулярное выражение заменить строку
s = "Ralph was walking down the street, he saw Mary and fell in love with her. Judy loves her hair."
У меня есть ArrayList<ArrayList<String>> anaphora
с правильными спичек и номером предложения и ArrayList<String> sentences
с предложениями от s
. Оба выглядят так:
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.
Проблема возникает при попытке заменить подстроки.
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));
}
выход будет:
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.
Ожидаемый результат будет таким образом, что 'он' заменяется на 'Ральф':
Ralph was walking down the street, Ralph saw Mary and fell in love with her.
Вопрос Как Я исправляю свое регулярное выражение так, чтобы ТОЛЬКО был заменен правильный «он»?
Что вы пытаетесь сделать? Можете ли вы предоставить пример CLEAR? – Eugene
Что ожидается выход? –
попробуйте использовать границу '\ b'. Ваш шаблон будет '\\ bhe \\ b' для соответствия точно' he'. для получения дополнительной информации см .: http: //www.regular-expressions.info/wordboundaries.html – D3V