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);