My regular expression is working properly here: https://regexr.com/4j143

However, when I try to use it in Apex it is not working:

String regExp = '/\\s{1,}(ORDER BY)\\s{1,}(ID)(\\s{1,}(ASC)){0,1}(\\s{1,}(NULLS)\\s{1,}(LAST)){0,1}\\s{0,},/gi';

System.debug(Pattern.matches(regExp, input));

What am I doing wrong? How do I fix it?


This has to do with Java's unfortunate implementation of matches() - it assumes the input is the entire string. You feed it a regex of /\\s{1,}...{0,},/gi hoping that matches() will return true if the pattern matches a part of the input string but the actual regex that gets executed is /^\\s{1,}...{0,},$/gi. That will not match your entire string because your string does not begin with one or more spaces.

Salesforce docs do explain this nuance:

A Matcher object finds matches in a subset of its input string called a region. The default region for a Matcher object is always the entirety of the input string.

With default region being the entire string, you need to revise your regex by adding segments that match text at the beginning and end of the string (before ORDER BY and after ASC|NULLS|LAST). Here's a simplified, single-backslashed version of your regex with matches() returning true on the region as entire input string:

(.*)\s+(ORDER BY)\s+(\w+,?\s+)+ASC

If only a portion of your string should be considered "input", the region() function referenced in the doc above will be useful.

  • 2
    Calling find will return true if you match just a substring. – Adrian Larson Aug 11 '19 at 1:51

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.