2

I am having a regex replace issue where the regex statement is matching non whole words. In the below example I have the word 'cormand &'. When I run the regex statement, it return 'corm &'. I am using the \b in the regex statement which according to the java definition says:

`Matches a word boundary. Boundaries are determined when a word character is NOT followed or NOT preceded with another word character.`

so if my regex statement is '\b&|and|llc\b', then the regex SHOULD NOT match on words within the actual word.

The goal of this function is to clean up account names and remove common company Suffixes and name values.

Below is the code to replicate the issue in the developer console.

public static String RegexReplaceAll(String input, List<String> stopWords , String replaceWith)
{
    // (?i) Case insentivive

    String regExp = '\\b';

    for (Integer i = 0; i < stopWords.size(); i++) 
    {
        String stopWord = stopWords[i];
        // If last index
        if(i + 1 == stopWords.size())
        {
            regExp += stopWord;
        }
        else
        {
            regExp += stopWord+'|';
        }
    }

    regExp += '\\b';

    System.debug('regExp');
    System.debug(regExp);

    return input.replaceAll(regExp, replaceWith);
}





String input = 'cormand & LLC';
String[] stopWords = new List<String>();
stopWords.add('&');
stopWords.add('and');
stopWords.add('llc');
stopWords.add('corporation');

String input2 = RegexReplaceAll(input,stopWords, '' );

System.debug(input2);

1 Answer 1

4

The OR operator matches the left and right sides as independent matches. x|y matches x or y. The \b operator is part of a match that matches a zero-width "character" that marks a transition between a non-word and word-character (and vice versa). That means your expression is parsed as:

Match \b& or and or llc\b.

This expression matches &hello, standard, magicalllc, etc.

What you're missing is a group (). A group evaluates everything inside of it, just like the mathematical version of parentheses. While abc|def matches abc or def, ab(c|d)ef matches abcef or abdef, but not abcdef.

That means you're looking for \b(&|and|llc)\b, which is parsed as:

Match a word boundary, then match & or and or llc, and then match a word boundary.

You can write this method as:

public static String RegexReplaceAll(String input, List<String> stopWords , String replaceWith) {
  String regex = '\\b('+String.join(stopWords,'|')+')\\b';
  return input.replaceAll(regex, replaceWith);
}
1
  • This is not remove the "&" in the string. Try this on your console and youll see it is not matched. Aug 5 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.