I have a need to replicate SOQL's LIKE behaviour in Apex:

  • The % wildcard matches zero or more characters
  • The _ wildcard matches exactly one character
  • Case insensitive

including for cases where characters that have special meaning in regular expressions are used e.g. ( and ). What code do I need?

2 Answers 2


Couldn't find code for this anywhere - many examples ignore the possibility of characters that have special meaning in regular expressions being present.

This is what I ended up with as a solution, posted here in case it helps anyone else (and in case there is a better way to do it).

Updated per Derek F's feedback:

public static Boolean soqlLikeMatch(String candidate, String soqlLike) {

    // Escape regex special characters but keep the % and _ and space characters,
    // \w matches alphanumeric characters,
    // four backslashes translate to one escaped backslash i.e. \\
    String regex = soqlLike.replaceAll('([^\\w%_ ])', '\\\\$1');

    // Make case insensitive,
    // lock down start/end match,
    // convert SOQL wildcards to regex ones
    regex = '(?i)' + '^' + regex.replace('%', '.*?').replace('_', '.{1}?') + '$';

    return Pattern.matches(regex, candidate);
  • 1
    using (?i) at the start of your regex would turn on case-insensitive mode and thus remove the need to .toLowerCase()
    – Derek F
    Mar 31, 2021 at 11:13
  • Thanks Derek, I saw that but (like most of regex) isn't self documenting. I now have a good amount of test cases so will try it and update the answer.
    – Keith C
    Mar 31, 2021 at 12:40

If you're looking for a solution to compare, then this could help :

String mainString='main string ';
String searchString='str';
Boolean check=mainString.toLowerCase().indexOf(searchString.toLowerCase())>0);

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.