F. Moss
F. Moss

Reputation: 55

Using a regex to match a word ending in a comma but not within another word

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

Answers (3)

leoinstack
leoinstack

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

Abhijit Sarkar
Abhijit Sarkar

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

Derek Kaplan
Derek Kaplan

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

Related Questions