function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
csorrowscsorrows 

Please help - why isn't this pattern/matcher working?

I have been beating my head against the wall for hours trying to get this to work, and no luck.  I have some simple debug code in an Apex trigger that I'm trying to use to extract a series of six digits out of a serial number field.

 

But no matter how I code the pattern, it never matches.  Below is the sample code:

 

      String debugAssetSn = 'AA-104999';
      system.debug('debugAssetSn = ' + debugAssetSn);
      Pattern debugPatternAssetSnNumberOnly = Pattern.compile('([0-9]{6})');  // Why isn't this matching???
      Matcher debugMatcherAssetSnNumberOnly;
      debugMatcherAssetSnNumberOnly = debugPatternAssetSnNumberOnly.matcher(debugAssetSn);
      if (debugMatcherAssetSnNumberOnly.matches())
        {system.debug('Pattern DID match.');
         Integer debugAssetSnNumberOnly = integer.valueof(debugMatcherAssetSnNumberOnly.group(1));
         system.debug('debugAssetSnNumberOnly = ' + debugAssetSnNumberOnly);
        }
      else
        {system.debug('Pattern DID NOT match.');
        }

The Pattern.compile is very simple - Just a capture group of six digits.  But when I save the record and the trigger executes, it NEVER matches.

 

Even when I code the pattern compile as 'AA-104999' it never matches.  It always falls through to the debug 'Pattern DID NOT match' section.

 

Any thoughts would be GREATLY appreciated.  Thanks!

csorrowscsorrows

I think I might have figured it out.  I'm guessing patterns match the entire string, not just a substring like what I'm used to with Perl regex's.

 

I changed the pattern.compile line to the below, and it seems to work now:

 

Pattern debugPatternAssetSnNumberOnly = Pattern.compile('.*?([0-9]{6})');

 

I had to put a non-greedy character pattern at the beginning before it would match.  I'm guessing Java based patterns don't match substrings, but instead they match the entire string?  (I'm not a Java guy - I'm used to Perl's regex's).