For my example I am trying to replace ALL cases of “the” and “a” in a string with a space.
Including cases where these words are next to characters such as quotes and other punctuation
String oldString = "A test of the exp."
Pattern p = Pattern.compile("(((\\W|\\A)the(\\W|\\Z))|((\\W|\\A)a(\\W|\\Z)))",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(oldString);
newString = m.replaceAll(" ");
“A test of the exp.” returns “test of exp.” – Yeah!
“A test of the a exp.” returns “test of a exp.” – Boooo!
“The a in this test is a the.” returns “a in this test is the. – DoubleBoooo!
Any help would be greatly appreciated.
Thanks!
\bmatches at a word boundary (i. e. at the start or end of a word, where “word” is a sequence of alphanumeric characters).(?:...)is a non-capturing group, needed to separate the alternative words (in this caseaandthe) from the surrounding word boundary anchors.