I am using this regular expression:
String regex = '(\\d{11}|\\d{5} \\d{6}|\\+\\d{12})';
Pattern compiledPattern = Pattern.compile(regex);
Matcher match = compiledPattern.matcher('Inbound Call at 5:10:54 PM from 07970123123 (Jack Daniels)');
if (match.matches()) {
System.debug('MATCH');
String phone = match.group(1);
} else {
System.debug('MISS');
}
To extract the phone number from this String:
Inbound Call at 5:10:54 PM from 07970123123 (Jack Daniels)
When I test the Regex in:
It works fine.
But when I try and use it in Apex code, it does not find a match.
- What am I doing wrong?
- How can I fix it?
Best Answer
The documentation on the Matcher class should shed some light here.
The description for
matches()
states the followingMeanwhile the description for
find()
isfind()
is what you want to use here, since you want to match a portion of the input.An example for illustration