Search code examples
javaregexregex-replace

Regex to replace specific word/phrase in delimited list


I'm trying to get Java regex working to replace specific phrases in a comma-delimited list. It should also match/replace the leading comma, and any leading/trailing whitespace. I have to use strictly Java-based regex for this solution.

For example, I have a string of BIG BOAT , GREEN CAR,BIG BOAT, YELLOW TRUCK, BIG BOAT, AMAZON ECHO, BIG BOAT , BLUE CAR , BIG BOAT BLUE, TABLE, GLASSES, BIG BOAT and I have the regex of

(?:^|,\s*)BIG BOAT(?:$|[^,]*)

This seems to work in most cases. It matches all exact instances of BIG BOAT but incorrectly matches BIG BOAT BLUE.


Solution

  • Your initial regex was close to what you were trying to achieve. I just changed the end part (?:$|[^,]*) with \s*(?=,|$). Basically in the end bit, you want to match every BIG BOAT followed by zero or more white spaces, and then check if they're followed by a comma or be at the end of the string.

    Like so, your regex matches:

    • an eventual leading comma
    • zero or more white spaces
    • BIG BOAT
    • zero or more white spaces

    Here is the regex:

    (?:^|,\s*)BIG BOAT\s*(?=,|$)
    

    Here is a link to the regex at regex101