1 /*
2  * Copyright (C) 2011 The Libphonenumber Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.i18n.phonenumbers;
18 
19 import com.google.i18n.phonenumbers.PhoneNumberUtil.Leniency;
20 import com.google.i18n.phonenumbers.PhoneNumberUtil.MatchType;
21 import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
22 import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
23 import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
24 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
25 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
26 import com.google.i18n.phonenumbers.internal.RegexCache;
27 import java.lang.Character.UnicodeBlock;
28 import java.util.Iterator;
29 import java.util.NoSuchElementException;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 
33 /**
34  * A stateful class that finds and extracts telephone numbers from {@linkplain CharSequence text}.
35  * Instances can be created using the {@linkplain PhoneNumberUtil#findNumbers factory methods} in
36  * {@link PhoneNumberUtil}.
37  *
38  * <p>Vanity numbers (phone numbers using alphabetic digits such as <tt>1-800-SIX-FLAGS</tt> are
39  * not found.
40  *
41  * <p>This class is not thread-safe.
42  */
43 final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
44   /**
45    * The phone number pattern used by {@link #find}, similar to
46    * {@code PhoneNumberUtil.VALID_PHONE_NUMBER}, but with the following differences:
47    * <ul>
48    *   <li>All captures are limited in order to place an upper bound to the text matched by the
49    *       pattern.
50    * <ul>
51    *   <li>Leading punctuation / plus signs are limited.
52    *   <li>Consecutive occurrences of punctuation are limited.
53    *   <li>Number of digits is limited.
54    * </ul>
55    *   <li>No whitespace is allowed at the start or end.
56    *   <li>No alpha digits (vanity numbers such as 1-800-SIX-FLAGS) are currently supported.
57    * </ul>
58    */
59   private static final Pattern PATTERN;
60   /**
61    * Matches strings that look like publication pages. Example:
62    * <pre>Computing Complete Answers to Queries in the Presence of Limited Access Patterns.
63    * Chen Li. VLDB J. 12(3): 211-227 (2003).</pre>
64    *
65    * The string "211-227 (2003)" is not a telephone number.
66    */
67   private static final Pattern PUB_PAGES = Pattern.compile("\\d{1,5}-+\\d{1,5}\\s{0,4}\\(\\d{1,4}");
68 
69   /**
70    * Matches strings that look like dates using "/" as a separator. Examples: 3/10/2011, 31/10/96 or
71    * 08/31/95.
72    */
73   private static final Pattern SLASH_SEPARATED_DATES =
74       Pattern.compile("(?:(?:[0-3]?\\d/[01]?\\d)|(?:[01]?\\d/[0-3]?\\d))/(?:[12]\\d)?\\d{2}");
75 
76   /**
77    * Matches timestamps. Examples: "2012-01-02 08:00". Note that the reg-ex does not include the
78    * trailing ":\d\d" -- that is covered by TIME_STAMPS_SUFFIX.
79    */
80   private static final Pattern TIME_STAMPS =
81       Pattern.compile("[12]\\d{3}[-/]?[01]\\d[-/]?[0-3]\\d +[0-2]\\d$");
82   private static final Pattern TIME_STAMPS_SUFFIX = Pattern.compile(":[0-5]\\d");
83 
84   /**
85    * Pattern to check that brackets match. Opening brackets should be closed within a phone number.
86    * This also checks that there is something inside the brackets. Having no brackets at all is also
87    * fine.
88    */
89   private static final Pattern MATCHING_BRACKETS;
90 
91   /**
92    * Patterns used to extract phone numbers from a larger phone-number-like pattern. These are
93    * ordered according to specificity. For example, white-space is last since that is frequently
94    * used in numbers, not just to separate two numbers. We have separate patterns since we don't
95    * want to break up the phone-number-like text on more than one different kind of symbol at one
96    * time, although symbols of the same type (e.g. space) can be safely grouped together.
97    *
98    * Note that if there is a match, we will always check any text found up to the first match as
99    * well.
100    */
101   private static final Pattern[] INNER_MATCHES = {
102       // Breaks on the slash - e.g. "651-234-2345/332-445-1234"
103       Pattern.compile("/+(.*)"),
104       // Note that the bracket here is inside the capturing group, since we consider it part of the
105       // phone number. Will match a pattern like "(650) 223 3345 (754) 223 3321".
106       Pattern.compile("(\\([^(]*)"),
107       // Breaks on a hyphen - e.g. "12345 - 332-445-1234 is my number."
108       // We require a space on either side of the hyphen for it to be considered a separator.
109       Pattern.compile("(?:\\p{Z}-|-\\p{Z})\\p{Z}*(.+)"),
110       // Various types of wide hyphens. Note we have decided not to enforce a space here, since it's
111       // possible that it's supposed to be used to break two numbers without spaces, and we haven't
112       // seen many instances of it used within a number.
113       Pattern.compile("[\u2012-\u2015\uFF0D]\\p{Z}*(.+)"),
114       // Breaks on a full stop - e.g. "12345. 332-445-1234 is my number."
115       Pattern.compile("\\.+\\p{Z}*([^.]+)"),
116       // Breaks on space - e.g. "3324451234 8002341234"
117       Pattern.compile("\\p{Z}+(\\P{Z}+)")
118   };
119 
120   /**
121    * Punctuation that may be at the start of a phone number - brackets and plus signs.
122    */
123   private static final Pattern LEAD_CLASS;
124 
125   static {
126     /* Builds the MATCHING_BRACKETS and PATTERN regular expressions. The building blocks below exist
127      * to make the pattern more easily understood. */
128 
129     String openingParens = "(\\[\uFF08\uFF3B";
130     String closingParens = ")\\]\uFF09\uFF3D";
131     String nonParens = "[^" + openingParens + closingParens + "]";
132 
133     /* Limit on the number of pairs of brackets in a phone number. */
134     String bracketPairLimit = limit(0, 3);
135     /*
136      * An opening bracket at the beginning may not be closed, but subsequent ones should be.  It's
137      * also possible that the leading bracket was dropped, so we shouldn't be surprised if we see a
138      * closing bracket first. We limit the sets of brackets in a phone number to four.
139      */
140     MATCHING_BRACKETS = Pattern.compile(
141         "(?:[" + openingParens + "])?" + "(?:" + nonParens + "+" + "[" + closingParens + "])?"
142         + nonParens + "+"
143         + "(?:[" + openingParens + "]" + nonParens + "+[" + closingParens + "])" + bracketPairLimit
144         + nonParens + "*");
145 
146     /* Limit on the number of leading (plus) characters. */
147     String leadLimit = limit(0, 2);
148     /* Limit on the number of consecutive punctuation characters. */
149     String punctuationLimit = limit(0, 4);
150     /* The maximum number of digits allowed in a digit-separated block. As we allow all digits in a
151      * single block, set high enough to accommodate the entire national number and the international
152      * country code. */
153     int digitBlockLimit =
154         PhoneNumberUtil.MAX_LENGTH_FOR_NSN + PhoneNumberUtil.MAX_LENGTH_COUNTRY_CODE;
155     /* Limit on the number of blocks separated by punctuation. Uses digitBlockLimit since some
156      * formats use spaces to separate each digit. */
157     String blockLimit = limit(0, digitBlockLimit);
158 
159     /* A punctuation sequence allowing white space. */
160     String punctuation = "[" + PhoneNumberUtil.VALID_PUNCTUATION + "]" + punctuationLimit;
161     /* A digits block without punctuation. */
162     String digitSequence = "\\p{Nd}" + limit(1, digitBlockLimit);
163 
164     String leadClassChars = openingParens + PhoneNumberUtil.PLUS_CHARS;
165     String leadClass = "[" + leadClassChars + "]";
166     LEAD_CLASS = Pattern.compile(leadClass);
167 
168     /* Phone number pattern allowing optional punctuation. */
169     PATTERN = Pattern.compile(
170         "(?:" + leadClass + punctuation + ")" + leadLimit
171         + digitSequence + "(?:" + punctuation + digitSequence + ")" + blockLimit
172         + "(?:" + PhoneNumberUtil.EXTN_PATTERNS_FOR_MATCHING + ")?",
173         PhoneNumberUtil.REGEX_FLAGS);
174   }
175 
176   /** Returns a regular expression quantifier with an upper and lower limit. */
limit(int lower, int upper)177   private static String limit(int lower, int upper) {
178     if ((lower < 0) || (upper <= 0) || (upper < lower)) {
179       throw new IllegalArgumentException();
180     }
181     return "{" + lower + "," + upper + "}";
182   }
183 
184   /** The potential states of a PhoneNumberMatcher. */
185   private enum State {
186     NOT_READY, READY, DONE
187   }
188 
189   /** The phone number utility. */
190   private final PhoneNumberUtil phoneUtil;
191   /** The text searched for phone numbers. */
192   private final CharSequence text;
193   /**
194    * The region (country) to assume for phone numbers without an international prefix, possibly
195    * null.
196    */
197   private final String preferredRegion;
198   /** The degree of validation requested. */
199   private final Leniency leniency;
200   /** The maximum number of retries after matching an invalid number. */
201   private long maxTries;
202 
203   /** The iteration tristate. */
204   private State state = State.NOT_READY;
205   /** The last successful match, null unless in {@link State#READY}. */
206   private PhoneNumberMatch lastMatch = null;
207   /** The next index to start searching at. Undefined in {@link State#DONE}. */
208   private int searchIndex = 0;
209 
210   // A cache for frequently used country-specific regular expressions. Set to 32 to cover ~2-3
211   // countries being used for the same doc with ~10 patterns for each country. Some pages will have
212   // a lot more countries in use, but typically fewer numbers for each so expanding the cache for
213   // that use-case won't have a lot of benefit.
214   private final RegexCache regexCache = new RegexCache(32);
215 
216   /**
217    * Creates a new instance. See the factory methods in {@link PhoneNumberUtil} on how to obtain a
218    * new instance.
219    *
220    * @param util  the phone number util to use
221    * @param text  the character sequence that we will search, null for no text
222    * @param country  the country to assume for phone numbers not written in international format
223    *     (with a leading plus, or with the international dialing prefix of the specified region).
224    *     May be null or "ZZ" if only numbers with a leading plus should be
225    *     considered.
226    * @param leniency  the leniency to use when evaluating candidate phone numbers
227    * @param maxTries  the maximum number of invalid numbers to try before giving up on the text.
228    *     This is to cover degenerate cases where the text has a lot of false positives in it. Must
229    *     be {@code >= 0}.
230    */
PhoneNumberMatcher(PhoneNumberUtil util, CharSequence text, String country, Leniency leniency, long maxTries)231   PhoneNumberMatcher(PhoneNumberUtil util, CharSequence text, String country, Leniency leniency,
232       long maxTries) {
233 
234     if ((util == null) || (leniency == null)) {
235       throw new NullPointerException();
236     }
237     if (maxTries < 0) {
238       throw new IllegalArgumentException();
239     }
240     this.phoneUtil = util;
241     this.text = (text != null) ? text : "";
242     this.preferredRegion = country;
243     this.leniency = leniency;
244     this.maxTries = maxTries;
245   }
246 
247   /**
248    * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex}
249    * that represents a phone number. Returns the next match, null if none was found.
250    *
251    * @param index  the search index to start searching at
252    * @return  the phone number match found, null if none can be found
253    */
find(int index)254   private PhoneNumberMatch find(int index) {
255     Matcher matcher = PATTERN.matcher(text);
256     while ((maxTries > 0) && matcher.find(index)) {
257       int start = matcher.start();
258       CharSequence candidate = text.subSequence(start, matcher.end());
259 
260       // Check for extra numbers at the end.
261       // TODO: This is the place to start when trying to support extraction of multiple phone number
262       // from split notations (+41 79 123 45 67 / 68).
263       candidate = trimAfterFirstMatch(PhoneNumberUtil.SECOND_NUMBER_START_PATTERN, candidate);
264 
265       PhoneNumberMatch match = extractMatch(candidate, start);
266       if (match != null) {
267         return match;
268       }
269 
270       index = start + candidate.length();
271       maxTries--;
272     }
273 
274     return null;
275   }
276 
277   /**
278    * Trims away any characters after the first match of {@code pattern} in {@code candidate},
279    * returning the trimmed version.
280    */
trimAfterFirstMatch(Pattern pattern, CharSequence candidate)281   private static CharSequence trimAfterFirstMatch(Pattern pattern, CharSequence candidate) {
282     Matcher trailingCharsMatcher = pattern.matcher(candidate);
283     if (trailingCharsMatcher.find()) {
284       candidate = candidate.subSequence(0, trailingCharsMatcher.start());
285     }
286     return candidate;
287   }
288 
289   /**
290    * Helper method to determine if a character is a Latin-script letter or not. For our purposes,
291    * combining marks should also return true since we assume they have been added to a preceding
292    * Latin character.
293    */
294   // @VisibleForTesting
isLatinLetter(char letter)295   static boolean isLatinLetter(char letter) {
296     // Combining marks are a subset of non-spacing-mark.
297     if (!Character.isLetter(letter) && Character.getType(letter) != Character.NON_SPACING_MARK) {
298       return false;
299     }
300     UnicodeBlock block = UnicodeBlock.of(letter);
301     return block.equals(UnicodeBlock.BASIC_LATIN)
302         || block.equals(UnicodeBlock.LATIN_1_SUPPLEMENT)
303         || block.equals(UnicodeBlock.LATIN_EXTENDED_A)
304         || block.equals(UnicodeBlock.LATIN_EXTENDED_ADDITIONAL)
305         || block.equals(UnicodeBlock.LATIN_EXTENDED_B)
306         || block.equals(UnicodeBlock.COMBINING_DIACRITICAL_MARKS);
307   }
308 
isInvalidPunctuationSymbol(char character)309   private static boolean isInvalidPunctuationSymbol(char character) {
310     return character == '%' || Character.getType(character) == Character.CURRENCY_SYMBOL;
311   }
312 
313   /**
314    * Attempts to extract a match from a {@code candidate} character sequence.
315    *
316    * @param candidate  the candidate text that might contain a phone number
317    * @param offset  the offset of {@code candidate} within {@link #text}
318    * @return  the match found, null if none can be found
319    */
extractMatch(CharSequence candidate, int offset)320   private PhoneNumberMatch extractMatch(CharSequence candidate, int offset) {
321     // Skip a match that is more likely to be a date.
322     if (SLASH_SEPARATED_DATES.matcher(candidate).find()) {
323       return null;
324     }
325 
326     // Skip potential time-stamps.
327     if (TIME_STAMPS.matcher(candidate).find()) {
328       String followingText = text.toString().substring(offset + candidate.length());
329       if (TIME_STAMPS_SUFFIX.matcher(followingText).lookingAt()) {
330         return null;
331       }
332     }
333 
334     // Try to come up with a valid match given the entire candidate.
335     PhoneNumberMatch match = parseAndVerify(candidate, offset);
336     if (match != null) {
337       return match;
338     }
339 
340     // If that failed, try to find an "inner match" - there might be a phone number within this
341     // candidate.
342     return extractInnerMatch(candidate, offset);
343   }
344 
345   /**
346    * Attempts to extract a match from {@code candidate} if the whole candidate does not qualify as a
347    * match.
348    *
349    * @param candidate  the candidate text that might contain a phone number
350    * @param offset  the current offset of {@code candidate} within {@link #text}
351    * @return  the match found, null if none can be found
352    */
extractInnerMatch(CharSequence candidate, int offset)353   private PhoneNumberMatch extractInnerMatch(CharSequence candidate, int offset) {
354     for (Pattern possibleInnerMatch : INNER_MATCHES) {
355       Matcher groupMatcher = possibleInnerMatch.matcher(candidate);
356       boolean isFirstMatch = true;
357       while (groupMatcher.find() && maxTries > 0) {
358         if (isFirstMatch) {
359           // We should handle any group before this one too.
360           CharSequence group = trimAfterFirstMatch(
361               PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN,
362               candidate.subSequence(0, groupMatcher.start()));
363           PhoneNumberMatch match = parseAndVerify(group, offset);
364           if (match != null) {
365             return match;
366           }
367           maxTries--;
368           isFirstMatch = false;
369         }
370         CharSequence group = trimAfterFirstMatch(
371             PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN, groupMatcher.group(1));
372         PhoneNumberMatch match = parseAndVerify(group, offset + groupMatcher.start(1));
373         if (match != null) {
374           return match;
375         }
376         maxTries--;
377       }
378     }
379     return null;
380   }
381 
382   /**
383    * Parses a phone number from the {@code candidate} using {@link PhoneNumberUtil#parse} and
384    * verifies it matches the requested {@link #leniency}. If parsing and verification succeed, a
385    * corresponding {@link PhoneNumberMatch} is returned, otherwise this method returns null.
386    *
387    * @param candidate  the candidate match
388    * @param offset  the offset of {@code candidate} within {@link #text}
389    * @return  the parsed and validated phone number match, or null
390    */
parseAndVerify(CharSequence candidate, int offset)391   private PhoneNumberMatch parseAndVerify(CharSequence candidate, int offset) {
392     try {
393       // Check the candidate doesn't contain any formatting which would indicate that it really
394       // isn't a phone number.
395       if (!MATCHING_BRACKETS.matcher(candidate).matches() || PUB_PAGES.matcher(candidate).find()) {
396         return null;
397       }
398 
399       // If leniency is set to VALID or stricter, we also want to skip numbers that are surrounded
400       // by Latin alphabetic characters, to skip cases like abc8005001234 or 8005001234def.
401       if (leniency.compareTo(Leniency.VALID) >= 0) {
402         // If the candidate is not at the start of the text, and does not start with phone-number
403         // punctuation, check the previous character.
404         if (offset > 0 && !LEAD_CLASS.matcher(candidate).lookingAt()) {
405           char previousChar = text.charAt(offset - 1);
406           // We return null if it is a latin letter or an invalid punctuation symbol.
407           if (isInvalidPunctuationSymbol(previousChar) || isLatinLetter(previousChar)) {
408             return null;
409           }
410         }
411         int lastCharIndex = offset + candidate.length();
412         if (lastCharIndex < text.length()) {
413           char nextChar = text.charAt(lastCharIndex);
414           if (isInvalidPunctuationSymbol(nextChar) || isLatinLetter(nextChar)) {
415             return null;
416           }
417         }
418       }
419 
420       PhoneNumber number = phoneUtil.parseAndKeepRawInput(candidate, preferredRegion);
421 
422       if (leniency.verify(number, candidate, phoneUtil, this)) {
423         // We used parseAndKeepRawInput to create this number, but for now we don't return the extra
424         // values parsed. TODO: stop clearing all values here and switch all users over
425         // to using rawInput() rather than the rawString() of PhoneNumberMatch.
426         number.clearCountryCodeSource();
427         number.clearRawInput();
428         number.clearPreferredDomesticCarrierCode();
429         return new PhoneNumberMatch(offset, candidate.toString(), number);
430       }
431     } catch (NumberParseException e) {
432       // ignore and continue
433     }
434     return null;
435   }
436 
437   /**
438    * Small helper interface such that the number groups can be checked according to different
439    * criteria, both for our default way of performing formatting and for any alternate formats we
440    * may want to check.
441    */
442   interface NumberGroupingChecker {
443     /**
444      * Returns true if the groups of digits found in our candidate phone number match our
445      * expectations.
446      *
447      * @param number  the original number we found when parsing
448      * @param normalizedCandidate  the candidate number, normalized to only contain ASCII digits,
449      *     but with non-digits (spaces etc) retained
450      * @param expectedNumberGroups  the groups of digits that we would expect to see if we
451      *     formatted this number
452      */
checkGroups(PhoneNumberUtil util, PhoneNumber number, StringBuilder normalizedCandidate, String[] expectedNumberGroups)453     boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
454                         StringBuilder normalizedCandidate, String[] expectedNumberGroups);
455   }
456 
allNumberGroupsRemainGrouped(PhoneNumberUtil util, PhoneNumber number, StringBuilder normalizedCandidate, String[] formattedNumberGroups)457   static boolean allNumberGroupsRemainGrouped(PhoneNumberUtil util,
458                                               PhoneNumber number,
459                                               StringBuilder normalizedCandidate,
460                                               String[] formattedNumberGroups) {
461     int fromIndex = 0;
462     if (number.getCountryCodeSource() != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
463       // First skip the country code if the normalized candidate contained it.
464       String countryCode = Integer.toString(number.getCountryCode());
465       fromIndex = normalizedCandidate.indexOf(countryCode) + countryCode.length();
466     }
467     // Check each group of consecutive digits are not broken into separate groupings in the
468     // {@code normalizedCandidate} string.
469     for (int i = 0; i < formattedNumberGroups.length; i++) {
470       // Fails if the substring of {@code normalizedCandidate} starting from {@code fromIndex}
471       // doesn't contain the consecutive digits in formattedNumberGroups[i].
472       fromIndex = normalizedCandidate.indexOf(formattedNumberGroups[i], fromIndex);
473       if (fromIndex < 0) {
474         return false;
475       }
476       // Moves {@code fromIndex} forward.
477       fromIndex += formattedNumberGroups[i].length();
478       if (i == 0 && fromIndex < normalizedCandidate.length()) {
479         // We are at the position right after the NDC. We get the region used for formatting
480         // information based on the country code in the phone number, rather than the number itself,
481         // as we do not need to distinguish between different countries with the same country
482         // calling code and this is faster.
483         String region = util.getRegionCodeForCountryCode(number.getCountryCode());
484         if (util.getNddPrefixForRegion(region, true) != null
485             && Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
486           // This means there is no formatting symbol after the NDC. In this case, we only
487           // accept the number if there is no formatting symbol at all in the number, except
488           // for extensions. This is only important for countries with national prefixes.
489           String nationalSignificantNumber = util.getNationalSignificantNumber(number);
490           return normalizedCandidate.substring(fromIndex - formattedNumberGroups[i].length())
491               .startsWith(nationalSignificantNumber);
492         }
493       }
494     }
495     // The check here makes sure that we haven't mistakenly already used the extension to
496     // match the last group of the subscriber number. Note the extension cannot have
497     // formatting in-between digits.
498     return normalizedCandidate.substring(fromIndex).contains(number.getExtension());
499   }
500 
allNumberGroupsAreExactlyPresent(PhoneNumberUtil util, PhoneNumber number, StringBuilder normalizedCandidate, String[] formattedNumberGroups)501   static boolean allNumberGroupsAreExactlyPresent(PhoneNumberUtil util,
502                                                   PhoneNumber number,
503                                                   StringBuilder normalizedCandidate,
504                                                   String[] formattedNumberGroups) {
505     String[] candidateGroups =
506         PhoneNumberUtil.NON_DIGITS_PATTERN.split(normalizedCandidate.toString());
507     // Set this to the last group, skipping it if the number has an extension.
508     int candidateNumberGroupIndex =
509         number.hasExtension() ? candidateGroups.length - 2 : candidateGroups.length - 1;
510     // First we check if the national significant number is formatted as a block.
511     // We use contains and not equals, since the national significant number may be present with
512     // a prefix such as a national number prefix, or the country code itself.
513     if (candidateGroups.length == 1
514         || candidateGroups[candidateNumberGroupIndex].contains(
515             util.getNationalSignificantNumber(number))) {
516       return true;
517     }
518     // Starting from the end, go through in reverse, excluding the first group, and check the
519     // candidate and number groups are the same.
520     for (int formattedNumberGroupIndex = (formattedNumberGroups.length - 1);
521          formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0;
522          formattedNumberGroupIndex--, candidateNumberGroupIndex--) {
523       if (!candidateGroups[candidateNumberGroupIndex].equals(
524           formattedNumberGroups[formattedNumberGroupIndex])) {
525         return false;
526       }
527     }
528     // Now check the first group. There may be a national prefix at the start, so we only check
529     // that the candidate group ends with the formatted number group.
530     return (candidateNumberGroupIndex >= 0
531         && candidateGroups[candidateNumberGroupIndex].endsWith(formattedNumberGroups[0]));
532   }
533 
534   /**
535    * Helper method to get the national-number part of a number, formatted without any national
536    * prefix, and return it as a set of digit blocks that would be formatted together following
537    * standard formatting rules.
538    */
getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number)539   private static String[] getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number) {
540     // This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of
541     // digits.
542     String rfc3966Format = util.format(number, PhoneNumberFormat.RFC3966);
543     // We remove the extension part from the formatted string before splitting it into different
544     // groups.
545     int endIndex = rfc3966Format.indexOf(';');
546     if (endIndex < 0) {
547       endIndex = rfc3966Format.length();
548     }
549     // The country-code will have a '-' following it.
550     int startIndex = rfc3966Format.indexOf('-') + 1;
551     return rfc3966Format.substring(startIndex, endIndex).split("-");
552   }
553 
554   /**
555    * Helper method to get the national-number part of a number, formatted without any national
556    * prefix, and return it as a set of digit blocks that should be formatted together according to
557    * the formatting pattern passed in.
558    */
getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number, NumberFormat formattingPattern)559   private static String[] getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number,
560                                                   NumberFormat formattingPattern) {
561     // If a format is provided, we format the NSN only, and split that according to the separator.
562     String nationalSignificantNumber = util.getNationalSignificantNumber(number);
563     return util.formatNsnUsingPattern(nationalSignificantNumber,
564                                       formattingPattern, PhoneNumberFormat.RFC3966).split("-");
565   }
566 
checkNumberGroupingIsValid( PhoneNumber number, CharSequence candidate, PhoneNumberUtil util, NumberGroupingChecker checker)567   boolean checkNumberGroupingIsValid(
568       PhoneNumber number, CharSequence candidate, PhoneNumberUtil util,
569       NumberGroupingChecker checker) {
570     StringBuilder normalizedCandidate =
571         PhoneNumberUtil.normalizeDigits(candidate, true /* keep non-digits */);
572     String[] formattedNumberGroups = getNationalNumberGroups(util, number);
573     if (checker.checkGroups(util, number, normalizedCandidate, formattedNumberGroups)) {
574       return true;
575     }
576     // If this didn't pass, see if there are any alternate formats that match, and try them instead.
577     PhoneMetadata alternateFormats =
578         MetadataManager.getAlternateFormatsForCountry(number.getCountryCode());
579     String nationalSignificantNumber = util.getNationalSignificantNumber(number);
580     if (alternateFormats != null) {
581       for (NumberFormat alternateFormat : alternateFormats.getNumberFormatList()) {
582         if (alternateFormat.getLeadingDigitsPatternCount() > 0) {
583           // There is only one leading digits pattern for alternate formats.
584           Pattern pattern =
585               regexCache.getPatternForRegex(alternateFormat.getLeadingDigitsPattern(0));
586           if (!pattern.matcher(nationalSignificantNumber).lookingAt()) {
587             // Leading digits don't match; try another one.
588             continue;
589           }
590         }
591         formattedNumberGroups = getNationalNumberGroups(util, number, alternateFormat);
592         if (checker.checkGroups(util, number, normalizedCandidate, formattedNumberGroups)) {
593           return true;
594         }
595       }
596     }
597     return false;
598   }
599 
containsMoreThanOneSlashInNationalNumber(PhoneNumber number, String candidate)600   static boolean containsMoreThanOneSlashInNationalNumber(PhoneNumber number, String candidate) {
601     int firstSlashInBodyIndex = candidate.indexOf('/');
602     if (firstSlashInBodyIndex < 0) {
603       // No slashes, this is okay.
604       return false;
605     }
606     // Now look for a second one.
607     int secondSlashInBodyIndex = candidate.indexOf('/', firstSlashInBodyIndex + 1);
608     if (secondSlashInBodyIndex < 0) {
609       // Only one slash, this is okay.
610       return false;
611     }
612 
613     // If the first slash is after the country calling code, this is permitted.
614     boolean candidateHasCountryCode =
615         (number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN
616          || number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
617     if (candidateHasCountryCode
618         && PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(0, firstSlashInBodyIndex))
619             .equals(Integer.toString(number.getCountryCode()))) {
620       // Any more slashes and this is illegal.
621       return candidate.substring(secondSlashInBodyIndex + 1).contains("/");
622     }
623     return true;
624   }
625 
containsOnlyValidXChars( PhoneNumber number, String candidate, PhoneNumberUtil util)626   static boolean containsOnlyValidXChars(
627       PhoneNumber number, String candidate, PhoneNumberUtil util) {
628     // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
629     // national significant number or (2) an extension sign, in which case they always precede the
630     // extension number. We assume a carrier code is more than 1 digit, so the first case has to
631     // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x'
632     // or 'X'. We ignore the character if it appears as the last character of the string.
633     for (int index = 0; index < candidate.length() - 1; index++) {
634       char charAtIndex = candidate.charAt(index);
635       if (charAtIndex == 'x' || charAtIndex == 'X') {
636         char charAtNextIndex = candidate.charAt(index + 1);
637         if (charAtNextIndex == 'x' || charAtNextIndex == 'X') {
638           // This is the carrier code case, in which the 'X's always precede the national
639           // significant number.
640           index++;
641           if (util.isNumberMatch(number, candidate.substring(index)) != MatchType.NSN_MATCH) {
642             return false;
643           }
644         // This is the extension sign case, in which the 'x' or 'X' should always precede the
645         // extension number.
646         } else if (!PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(index)).equals(
647             number.getExtension())) {
648           return false;
649         }
650       }
651     }
652     return true;
653   }
654 
isNationalPrefixPresentIfRequired(PhoneNumber number, PhoneNumberUtil util)655   static boolean isNationalPrefixPresentIfRequired(PhoneNumber number, PhoneNumberUtil util) {
656     // First, check how we deduced the country code. If it was written in international format, then
657     // the national prefix is not required.
658     if (number.getCountryCodeSource() != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
659       return true;
660     }
661     String phoneNumberRegion =
662         util.getRegionCodeForCountryCode(number.getCountryCode());
663     PhoneMetadata metadata = util.getMetadataForRegion(phoneNumberRegion);
664     if (metadata == null) {
665       return true;
666     }
667     // Check if a national prefix should be present when formatting this number.
668     String nationalNumber = util.getNationalSignificantNumber(number);
669     NumberFormat formatRule =
670         util.chooseFormattingPatternForNumber(metadata.getNumberFormatList(), nationalNumber);
671     // To do this, we check that a national prefix formatting rule was present and that it wasn't
672     // just the first-group symbol ($1) with punctuation.
673     if ((formatRule != null) && formatRule.getNationalPrefixFormattingRule().length() > 0) {
674       if (formatRule.getNationalPrefixOptionalWhenFormatting()) {
675         // The national-prefix is optional in these cases, so we don't need to check if it was
676         // present.
677         return true;
678       }
679       if (PhoneNumberUtil.formattingRuleHasFirstGroupOnly(
680           formatRule.getNationalPrefixFormattingRule())) {
681         // National Prefix not needed for this number.
682         return true;
683       }
684       // Normalize the remainder.
685       String rawInputCopy = PhoneNumberUtil.normalizeDigitsOnly(number.getRawInput());
686       StringBuilder rawInput = new StringBuilder(rawInputCopy);
687       // Check if we found a national prefix and/or carrier code at the start of the raw input, and
688       // return the result.
689       return util.maybeStripNationalPrefixAndCarrierCode(rawInput, metadata, null);
690     }
691     return true;
692   }
693 
694   @Override
hasNext()695   public boolean hasNext() {
696     if (state == State.NOT_READY) {
697       lastMatch = find(searchIndex);
698       if (lastMatch == null) {
699         state = State.DONE;
700       } else {
701         searchIndex = lastMatch.end();
702         state = State.READY;
703       }
704     }
705     return state == State.READY;
706   }
707 
708   @Override
next()709   public PhoneNumberMatch next() {
710     // Check the state and find the next match as a side-effect if necessary.
711     if (!hasNext()) {
712       throw new NoSuchElementException();
713     }
714 
715     // Don't retain that memory any longer than necessary.
716     PhoneNumberMatch result = lastMatch;
717     lastMatch = null;
718     state = State.NOT_READY;
719     return result;
720   }
721 
722   /**
723    * Always throws {@link UnsupportedOperationException} as removal is not supported.
724    */
725   @Override
remove()726   public void remove() {
727     throw new UnsupportedOperationException();
728   }
729 }
730