1

I have input string to process of the format

xxx:xxx:xxx:xxx:filters:6:item:xxx

Where xxx could by any combination of alphanumerics and underscore.

I am trying to capture the number between filters and item using regular expressions.

I have the regular expression \\S*filters:(\\d+):item\\S* and it matches OK but I cannot work out how to extract the number.

The test code

Pattern myPattern = Pattern.compile('\\S*filters:(\\d+):item\\S*');
Matcher myMatcher = myPattern.matcher('aaaaab:filters:3:item:foo');
system.debug(myMatcher.matches());
system.debug(myMatcher.groupCount());
system.debug(myMatcher.group(0));

outputs the following:

true
1
aaaaab:filters:3:item:foo

as you see, the group has captured who whole string, not just the number which I want.

How do I get the number?

2

The first match is the entire pattern. So in this case you'd want the second match. Try:

Pattern myPattern = Pattern.compile('\\S*filters:(\\d+):item\\S*');
Matcher myMatcher = myPattern.matcher('aaaaab:filters:3:item:foo');
system.debug(myMatcher.group(1));

And you'll get the output 3.

It's a bit confusing since the group count says there is only one group. However, that's the way the group count is defined. It doesn't include the entire pattern. (See: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_pattern_and_matcher_matcher_methods.htm#apex_System_Matcher_groupCount)

Kudos for getting the regex right. I always find that the hard part.

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.