4

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?
0

2 Answers 2

9

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
7

It does work - but only if you use the method that yields a substring match.

String input = 'Inbound Call at 5:10:54 PM from 07970123123 (Jack Daniels)';
String regex = '(\\d{11}|\\d{5} \\d{6}|\\+\\d{12})';

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);

System.debug('Find: ' + m.find()); // true
System.debug('Group: ' + m.group()); // 07970123123
System.debug('Matches: ' + m.matches()); // false

Matcher.matches() asks to find a match against the entire input region. Matcher.find() locates a group within the input region.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.