Reputation: 55
I want to use a regex to achieve two objectives: match a string only when it is a complete word (don't match "on" inside of "contact"), and match strings that end with a comma or period.
This is an example. It is meant to find the string (str2) in str and replace it with the same string surrounded by parenthesis.
while(scan2.hasNext()) {
String str2 = scan2.next();
str = str.replaceAll("\\b" + str2 + "\\b", "(" + str2 + ")");
}
It does avoid matching strings within words, but it ignores strings that end in a comma or period.
How would I do this?
Upvotes: 0
Views: 2176
Reputation: 26
The following regex matches string ending with comma/period or string composed by a single complete word:
(?s)(^(?<A>\b\w+\b)$)|((?s)^(?<B>.+(?<=[,.]))$)
See also https://regex101.com/r/E78rQV/1/ for more explanations.
Upvotes: 0
Reputation: 24518
public class Main {
public static void main(String[] args) {
System.out.println(replace("upon contact", "on"));
System.out.println(replace("upon contact,", "contact"));
System.out.println(replace("upon contact", "contact"));
}
private static String replace(String s1, String s2) {
return s1.replaceAll(String.format("\\b(%s)\\b(?=[.,])", s2), "\\($1\\)");
}
}
upon contact // matches only complete words
upon (contact), // replaces match with (match)
upon contact // only matches if ends with , or .
Upvotes: 2
Reputation: 138
I took the liberty of adding exclamation point and question mark. Brackets means it will match for any of the characters inside the brackets.
str = str.replaceAll("\\b" + str2 + "[\\b.,!?]", "(" + str2 + ")");
Upvotes: -1