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.