1

I'm working on regex in order to replace some strings

public static String removeValuesByRegex(String input, Pattern pattern, String replaceWith){
 String result;

 Matcher matcher = pattern.matcher(input);

 return result = matcher.replaceAll(replaceWith).trim();
}

Then in my test class im doing

String keywords = 'LLC|Corp|Corporation';
Pattern pattern = Pattern.compile('(?i)(?<= |^)\'|' + keyWords + '\'|(?= |$)');

String stringResult = UtilString.removeValuesByRegex('Corporation This Has a Name LLC AND CoRp ', pattern, '');

The output will come out as

oration This Has a Name AND

What appears to be happening is the regex is finding Corp in Corporation and removing "Corp" which then messed up the the Corporation comparison, is this a regex update or can I not do this approach?

1 Answer 1

2

You can use word boundaries if you want to match whole words:

String keywords = '\\b(LLC|Corp|Corporation)\\b';

Note that the \\ is necessary because source code must be escaped (this translates to a literal \b in the string, which is what the regular expression engine expects).

6
  • Thanks but how could I implement that with my current lookbehind/ahead pattern?
    – EricSSH
    Commented Mar 14, 2019 at 19:45
  • @EricSSH I'm not sure what you're trying to do with your implementation, it doesn't seem to be necessary? \b matches word boundaries, which is what you appear to be trying to do.
    – sfdcfox
    Commented Mar 14, 2019 at 19:53
  • The key words will be different based on what the metadata object says it should be so I believe I need to update my regex pattern to make it be an exact match regex101.com/r/w6mUEm/2
    – EricSSH
    Commented Mar 14, 2019 at 20:47
  • I do see what your saying, just not sure why it isn't finding matches regex101.com/r/SBWNjK/1
    – EricSSH
    Commented Mar 14, 2019 at 21:01
  • @EricSSH Apex and regexp both use the backslash as an escape character. This means a regexp in Apex source code must have their backslashes escaped. On the site you linked, you would use just \b instead.
    – sfdcfox
    Commented Mar 14, 2019 at 21:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .