java - Using a regex to match a word ending in a comma but not within another word -
i want use regex achieve 2 objectives: match string when complete word (don't match "on" inside of "contact"), , match strings end comma or period.
this example. meant find string (str2) in str , replace same string surrounded parenthesis.
while(scan2.hasnext()) { string str2 = scan2.next(); str = str.replaceall("\\b" + str2 + "\\b", "(" + str2 + ")"); }
it avoid matching strings within words, ignores strings end in comma or period.
how this?
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 complete words
upon (contact), // replaces match (match)
upon contact // matches if ends , or .
Comments
Post a Comment