Preamble
I know (based on this question "No match found" when using Regex in Apex), that I can avoid "No Match Found" by wrapping the results in:
if(pm.matches()){ //Code }
However, this appears to be specific to when the Regex is a complete match to the string.
Scenario
I am trying to find a substring within the string(s), a set of numbers between parenthesis, like this (500). I want to return only the numbers inside the parenthesis, to store this number in a Salesforce number field.
I know I can use pm.find()
, but it appears that if it does not find anything, it throws the "No Match Found" error instead of gracefully returning false, meaning I cannot do this:
if(pm.find()){
// Code
}
The code above would still error when trying to do pm.find
on a string with no results found.
ISSUE
I want to be able to put in any string and pull out the number IF one exists, but with this "No Match Found" issue I can't throw a string at it unless that string is guaranteed to have at least one set of numbers inside a parenthesis. Any string that has no numbers will throw the error. I considered putting this in a
try{}catch{}
block and just catching the errors gracefully, but this doesn't seem like the correct approach.How can I work around this to be able to check any string but only set the number field in Salesforce in instances where a result is found in the string?
I've included some execute anonymous code below that shows a success and a failure, for reference:
SUCCESS
String str = 'Text Messaging Plan (500)';
Pattern p = Pattern.compile('.+\\((\\d+)');
Matcher pm = p.matcher(str);
System.debug('Find? ' + pm.find());
System.debug('PM Group 1: ' + pm.group(1));
FAILURE
String str = 'Text Messaging Plan (abc)';
Pattern p = Pattern.compile('.+\\((\\d+)');
Matcher pm = p.matcher(str);
System.debug('Find? ' + pm.find()); // FAILS HERE
System.debug('PM Group 1: ' + pm.group(1));