[SalesForce] Regular Expression matches returns false

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.

  1. What am I doing wrong?
  2. How can I fix it?

Best Answer

The documentation on the Matcher class should shed some light here.

The description for matches() states the following

Attempts to match the entire region against the pattern.

Meanwhile the description for find() is

Attempts to find the next subsequence of the input sequence that matches the pattern. This method returns true if a subsequence of the input sequence matches this Matcher object's pattern.

find() is what you want to use here, since you want to match a portion of the input.

An example for illustration

String regex = '(\\d{11}|\\d{5} \\d{6}|\\+\\d{12})';
Pattern msgPattern = Pattern.compile(regex);
Matcher m1 = msgPattern.matcher('Inbound Call at 5:10:54 PM from 07970123123 (Jack Daniels)');

system.debug(m1.matches()); // displays false
system.debug(m1.find()); // displays true
Related Topic