Home | History | Annotate | Download | only in phonenumbers
      1 /*
      2  * Copyright (C) 2011 Google Inc.
      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.android.i18n.phonenumbers;
     18 
     19 import com.android.i18n.phonenumbers.PhoneNumberUtil.Leniency;
     20 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber;
     21 
     22 import java.lang.Character.UnicodeBlock;
     23 import java.util.Iterator;
     24 import java.util.NoSuchElementException;
     25 import java.util.regex.Matcher;
     26 import java.util.regex.Pattern;
     27 
     28 /**
     29  * A stateful class that finds and extracts telephone numbers from {@linkplain CharSequence text}.
     30  * Instances can be created using the {@linkplain PhoneNumberUtil#findNumbers factory methods} in
     31  * {@link PhoneNumberUtil}.
     32  *
     33  * <p>Vanity numbers (phone numbers using alphabetic digits such as <tt>1-800-SIX-FLAGS</tt> are
     34  * not found.
     35  *
     36  * <p>This class is not thread-safe.
     37  *
     38  * @author Tom Hofmann
     39  */
     40 final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
     41   /**
     42    * The phone number pattern used by {@link #find}, similar to
     43    * {@code PhoneNumberUtil.VALID_PHONE_NUMBER}, but with the following differences:
     44    * <ul>
     45    *   <li>All captures are limited in order to place an upper bound to the text matched by the
     46    *       pattern.
     47    * <ul>
     48    *   <li>Leading punctuation / plus signs are limited.
     49    *   <li>Consecutive occurrences of punctuation are limited.
     50    *   <li>Number of digits is limited.
     51    * </ul>
     52    *   <li>No whitespace is allowed at the start or end.
     53    *   <li>No alpha digits (vanity numbers such as 1-800-SIX-FLAGS) are currently supported.
     54    * </ul>
     55    */
     56   private static final Pattern PATTERN;
     57   /**
     58    * Matches strings that look like publication pages. Example:
     59    * <pre>Computing Complete Answers to Queries in the Presence of Limited Access Patterns.
     60    * Chen Li. VLDB J. 12(3): 211-227 (2003).</pre>
     61    *
     62    * The string "211-227 (2003)" is not a telephone number.
     63    */
     64   private static final Pattern PUB_PAGES = Pattern.compile("\\d{1,5}-+\\d{1,5}\\s{0,4}\\(\\d{1,4}");
     65 
     66   /**
     67    * Matches strings that look like dates using "/" as a separator. Examples: 3/10/2011, 31/10/96 or
     68    * 08/31/95.
     69    */
     70   private static final Pattern SLASH_SEPARATED_DATES =
     71       Pattern.compile("(?:(?:[0-3]?\\d/[01]?\\d)|(?:[01]?\\d/[0-3]?\\d))/(?:[12]\\d)?\\d{2}");
     72 
     73   /**
     74    * Pattern to check that brackets match. Opening brackets should be closed within a phone number.
     75    * This also checks that there is something inside the brackets. Having no brackets at all is also
     76    * fine.
     77    */
     78   private static final Pattern MATCHING_BRACKETS;
     79 
     80   /**
     81    * Matches white-space, which may indicate the end of a phone number and the start of something
     82    * else (such as a neighbouring zip-code). If white-space is found, continues to match all
     83    * characters that are not typically used to start a phone number.
     84    */
     85   private static final Pattern GROUP_SEPARATOR;
     86 
     87   /**
     88    * Punctuation that may be at the start of a phone number - brackets and plus signs.
     89    */
     90   private static final Pattern LEAD_CLASS;
     91 
     92   static {
     93     /* Builds the MATCHING_BRACKETS and PATTERN regular expressions. The building blocks below exist
     94      * to make the pattern more easily understood. */
     95 
     96     String openingParens = "(\\[\uFF08\uFF3B";
     97     String closingParens = ")\\]\uFF09\uFF3D";
     98     String nonParens = "[^" + openingParens + closingParens + "]";
     99 
    100     /* Limit on the number of pairs of brackets in a phone number. */
    101     String bracketPairLimit = limit(0, 3);
    102     /*
    103      * An opening bracket at the beginning may not be closed, but subsequent ones should be.  It's
    104      * also possible that the leading bracket was dropped, so we shouldn't be surprised if we see a
    105      * closing bracket first. We limit the sets of brackets in a phone number to four.
    106      */
    107     MATCHING_BRACKETS = Pattern.compile(
    108         "(?:[" + openingParens + "])?" + "(?:" + nonParens + "+" + "[" + closingParens + "])?" +
    109         nonParens + "+" +
    110         "(?:[" + openingParens + "]" + nonParens + "+[" + closingParens + "])" + bracketPairLimit +
    111         nonParens + "*");
    112 
    113     /* Limit on the number of leading (plus) characters. */
    114     String leadLimit = limit(0, 2);
    115     /* Limit on the number of consecutive punctuation characters. */
    116     String punctuationLimit = limit(0, 4);
    117     /* The maximum number of digits allowed in a digit-separated block. As we allow all digits in a
    118      * single block, set high enough to accommodate the entire national number and the international
    119      * country code. */
    120     int digitBlockLimit =
    121         PhoneNumberUtil.MAX_LENGTH_FOR_NSN + PhoneNumberUtil.MAX_LENGTH_COUNTRY_CODE;
    122     /* Limit on the number of blocks separated by punctuation. Uses digitBlockLimit since some
    123      * formats use spaces to separate each digit. */
    124     String blockLimit = limit(0, digitBlockLimit);
    125 
    126     /* A punctuation sequence allowing white space. */
    127     String punctuation = "[" + PhoneNumberUtil.VALID_PUNCTUATION + "]" + punctuationLimit;
    128     /* A digits block without punctuation. */
    129     String digitSequence = "\\p{Nd}" + limit(1, digitBlockLimit);
    130 
    131     String leadClassChars = openingParens + PhoneNumberUtil.PLUS_CHARS;
    132     String leadClass = "[" + leadClassChars + "]";
    133     LEAD_CLASS = Pattern.compile(leadClass);
    134     GROUP_SEPARATOR = Pattern.compile("\\p{Z}" + "[^" + leadClassChars  + "\\p{Nd}]*");
    135 
    136     /* Phone number pattern allowing optional punctuation. */
    137     PATTERN = Pattern.compile(
    138         "(?:" + leadClass + punctuation + ")" + leadLimit +
    139         digitSequence + "(?:" + punctuation + digitSequence + ")" + blockLimit +
    140         "(?:" + PhoneNumberUtil.EXTN_PATTERNS_FOR_MATCHING + ")?",
    141         PhoneNumberUtil.REGEX_FLAGS);
    142   }
    143 
    144   /** Returns a regular expression quantifier with an upper and lower limit. */
    145   private static String limit(int lower, int upper) {
    146     if ((lower < 0) || (upper <= 0) || (upper < lower)) {
    147       throw new IllegalArgumentException();
    148     }
    149     return "{" + lower + "," + upper + "}";
    150   }
    151 
    152   /** The potential states of a PhoneNumberMatcher. */
    153   private enum State {
    154     NOT_READY, READY, DONE
    155   }
    156 
    157   /** The phone number utility. */
    158   private final PhoneNumberUtil phoneUtil;
    159   /** The text searched for phone numbers. */
    160   private final CharSequence text;
    161   /**
    162    * The region (country) to assume for phone numbers without an international prefix, possibly
    163    * null.
    164    */
    165   private final String preferredRegion;
    166   /** The degree of validation requested. */
    167   private final Leniency leniency;
    168   /** The maximum number of retries after matching an invalid number. */
    169   private long maxTries;
    170 
    171   /** The iteration tristate. */
    172   private State state = State.NOT_READY;
    173   /** The last successful match, null unless in {@link State#READY}. */
    174   private PhoneNumberMatch lastMatch = null;
    175   /** The next index to start searching at. Undefined in {@link State#DONE}. */
    176   private int searchIndex = 0;
    177 
    178   /**
    179    * Creates a new instance. See the factory methods in {@link PhoneNumberUtil} on how to obtain a
    180    * new instance.
    181    *
    182    * @param util      the phone number util to use
    183    * @param text      the character sequence that we will search, null for no text
    184    * @param country   the country to assume for phone numbers not written in international format
    185    *                  (with a leading plus, or with the international dialing prefix of the
    186    *                  specified region). May be null or "ZZ" if only numbers with a
    187    *                  leading plus should be considered.
    188    * @param leniency  the leniency to use when evaluating candidate phone numbers
    189    * @param maxTries  the maximum number of invalid numbers to try before giving up on the text.
    190    *                  This is to cover degenerate cases where the text has a lot of false positives
    191    *                  in it. Must be {@code >= 0}.
    192    */
    193   PhoneNumberMatcher(PhoneNumberUtil util, CharSequence text, String country, Leniency leniency,
    194       long maxTries) {
    195 
    196     if ((util == null) || (leniency == null)) {
    197       throw new NullPointerException();
    198     }
    199     if (maxTries < 0) {
    200       throw new IllegalArgumentException();
    201     }
    202     this.phoneUtil = util;
    203     this.text = (text != null) ? text : "";
    204     this.preferredRegion = country;
    205     this.leniency = leniency;
    206     this.maxTries = maxTries;
    207   }
    208 
    209   public boolean hasNext() {
    210     if (state == State.NOT_READY) {
    211       lastMatch = find(searchIndex);
    212       if (lastMatch == null) {
    213         state = State.DONE;
    214       } else {
    215         searchIndex = lastMatch.end();
    216         state = State.READY;
    217       }
    218     }
    219     return state == State.READY;
    220   }
    221 
    222   public PhoneNumberMatch next() {
    223     // Check the state and find the next match as a side-effect if necessary.
    224     if (!hasNext()) {
    225       throw new NoSuchElementException();
    226     }
    227 
    228     // Don't retain that memory any longer than necessary.
    229     PhoneNumberMatch result = lastMatch;
    230     lastMatch = null;
    231     state = State.NOT_READY;
    232     return result;
    233   }
    234 
    235   /**
    236    * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex}
    237    * that represents a phone number. Returns the next match, null if none was found.
    238    *
    239    * @param index  the search index to start searching at
    240    * @return  the phone number match found, null if none can be found
    241    */
    242   private PhoneNumberMatch find(int index) {
    243     Matcher matcher = PATTERN.matcher(text);
    244     while ((maxTries > 0) && matcher.find(index)) {
    245       int start = matcher.start();
    246       CharSequence candidate = text.subSequence(start, matcher.end());
    247 
    248       // Check for extra numbers at the end.
    249       // TODO: This is the place to start when trying to support extraction of multiple phone number
    250       // from split notations (+41 79 123 45 67 / 68).
    251       candidate = trimAfterFirstMatch(PhoneNumberUtil.SECOND_NUMBER_START_PATTERN, candidate);
    252 
    253       PhoneNumberMatch match = extractMatch(candidate, start);
    254       if (match != null) {
    255         return match;
    256       }
    257 
    258       index = start + candidate.length();
    259       maxTries--;
    260     }
    261 
    262     return null;
    263   }
    264 
    265   /**
    266    * Trims away any characters after the first match of {@code pattern} in {@code candidate},
    267    * returning the trimmed version.
    268    */
    269   private static CharSequence trimAfterFirstMatch(Pattern pattern, CharSequence candidate) {
    270     Matcher trailingCharsMatcher = pattern.matcher(candidate);
    271     if (trailingCharsMatcher.find()) {
    272       candidate = candidate.subSequence(0, trailingCharsMatcher.start());
    273     }
    274     return candidate;
    275   }
    276 
    277   /**
    278    * Helper method to determine if a character is a Latin-script letter or not. For our purposes,
    279    * combining marks should also return true since we assume they have been added to a preceding
    280    * Latin character.
    281    */
    282   static boolean isLatinLetter(char letter) {
    283     // Combining marks are a subset of non-spacing-mark.
    284     if (!Character.isLetter(letter) && Character.getType(letter) != Character.NON_SPACING_MARK) {
    285       return false;
    286     }
    287     UnicodeBlock block = UnicodeBlock.of(letter);
    288     return block.equals(UnicodeBlock.BASIC_LATIN) ||
    289         block.equals(UnicodeBlock.LATIN_1_SUPPLEMENT) ||
    290         block.equals(UnicodeBlock.LATIN_EXTENDED_A) ||
    291         block.equals(UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) ||
    292         block.equals(UnicodeBlock.LATIN_EXTENDED_B) ||
    293         block.equals(UnicodeBlock.COMBINING_DIACRITICAL_MARKS);
    294   }
    295 
    296   private static boolean isCurrencySymbol(char character) {
    297     return Character.getType(character) == Character.CURRENCY_SYMBOL;
    298   }
    299 
    300   /**
    301    * Attempts to extract a match from a {@code candidate} character sequence.
    302    *
    303    * @param candidate  the candidate text that might contain a phone number
    304    * @param offset  the offset of {@code candidate} within {@link #text}
    305    * @return  the match found, null if none can be found
    306    */
    307   private PhoneNumberMatch extractMatch(CharSequence candidate, int offset) {
    308     // Skip a match that is more likely a publication page reference or a date.
    309     if (PUB_PAGES.matcher(candidate).find() || SLASH_SEPARATED_DATES.matcher(candidate).find()) {
    310       return null;
    311     }
    312 
    313     // Try to come up with a valid match given the entire candidate.
    314     String rawString = candidate.toString();
    315     PhoneNumberMatch match = parseAndVerify(rawString, offset);
    316     if (match != null) {
    317       return match;
    318     }
    319 
    320     // If that failed, try to find an "inner match" - there might be a phone number within this
    321     // candidate.
    322     return extractInnerMatch(rawString, offset);
    323   }
    324 
    325   /**
    326    * Attempts to extract a match from {@code candidate} if the whole candidate does not qualify as a
    327    * match.
    328    *
    329    * @param candidate  the candidate text that might contain a phone number
    330    * @param offset  the current offset of {@code candidate} within {@link #text}
    331    * @return  the match found, null if none can be found
    332    */
    333   private PhoneNumberMatch extractInnerMatch(String candidate, int offset) {
    334     // Try removing either the first or last "group" in the number and see if this gives a result.
    335     // We consider white space to be a possible indication of the start or end of the phone number.
    336     Matcher groupMatcher = GROUP_SEPARATOR.matcher(candidate);
    337 
    338     if (groupMatcher.find()) {
    339       // Try the first group by itself.
    340       CharSequence firstGroupOnly = candidate.substring(0, groupMatcher.start());
    341       firstGroupOnly = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN,
    342                                            firstGroupOnly);
    343       PhoneNumberMatch match = parseAndVerify(firstGroupOnly.toString(), offset);
    344       if (match != null) {
    345         return match;
    346       }
    347       maxTries--;
    348 
    349       int withoutFirstGroupStart = groupMatcher.end();
    350       // Try the rest of the candidate without the first group.
    351       CharSequence withoutFirstGroup = candidate.substring(withoutFirstGroupStart);
    352       withoutFirstGroup = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN,
    353                                               withoutFirstGroup);
    354       match = parseAndVerify(withoutFirstGroup.toString(), offset + withoutFirstGroupStart);
    355       if (match != null) {
    356         return match;
    357       }
    358       maxTries--;
    359 
    360       if (maxTries > 0) {
    361         int lastGroupStart = withoutFirstGroupStart;
    362         while (groupMatcher.find()) {
    363           // Find the last group.
    364           lastGroupStart = groupMatcher.start();
    365         }
    366         CharSequence withoutLastGroup = candidate.substring(0, lastGroupStart);
    367         withoutLastGroup = trimAfterFirstMatch(PhoneNumberUtil.UNWANTED_END_CHAR_PATTERN,
    368                                                withoutLastGroup);
    369         if (withoutLastGroup.equals(firstGroupOnly)) {
    370           // If there are only two groups, then the group "without the last group" is the same as
    371           // the first group. In these cases, we don't want to re-check the number group, so we exit
    372           // already.
    373           return null;
    374         }
    375         match = parseAndVerify(withoutLastGroup.toString(), offset);
    376         if (match != null) {
    377           return match;
    378         }
    379         maxTries--;
    380       }
    381     }
    382     return null;
    383   }
    384 
    385   /**
    386    * Parses a phone number from the {@code candidate} using {@link PhoneNumberUtil#parse} and
    387    * verifies it matches the requested {@link #leniency}. If parsing and verification succeed, a
    388    * corresponding {@link PhoneNumberMatch} is returned, otherwise this method returns null.
    389    *
    390    * @param candidate  the candidate match
    391    * @param offset  the offset of {@code candidate} within {@link #text}
    392    * @return  the parsed and validated phone number match, or null
    393    */
    394   private PhoneNumberMatch parseAndVerify(String candidate, int offset) {
    395     try {
    396       // Check the candidate doesn't contain any formatting which would indicate that it really
    397       // isn't a phone number.
    398       if (!MATCHING_BRACKETS.matcher(candidate).matches()) {
    399         return null;
    400       }
    401 
    402       // If leniency is set to VALID or stricter, we also want to skip numbers that are surrounded
    403       // by Latin alphabetic characters, to skip cases like abc8005001234 or 8005001234def.
    404       if (leniency.compareTo(Leniency.VALID) >= 0) {
    405         // If the candidate is not at the start of the text, and does not start with phone-number
    406         // punctuation, check the previous character.
    407         if (offset > 0 && !LEAD_CLASS.matcher(candidate).lookingAt()) {
    408           char previousChar = text.charAt(offset - 1);
    409           // We return null if it is a latin letter or a currency symbol.
    410           if (isCurrencySymbol(previousChar) || isLatinLetter(previousChar)) {
    411             return null;
    412           }
    413         }
    414         int lastCharIndex = offset + candidate.length();
    415         if (lastCharIndex < text.length()) {
    416           char nextChar = text.charAt(lastCharIndex);
    417           if (isCurrencySymbol(nextChar) || isLatinLetter(nextChar)) {
    418             return null;
    419           }
    420         }
    421       }
    422 
    423       PhoneNumber number = phoneUtil.parse(candidate, preferredRegion);
    424       if (leniency.verify(number, candidate, phoneUtil)) {
    425         return new PhoneNumberMatch(offset, candidate, number);
    426       }
    427     } catch (NumberParseException e) {
    428       // ignore and continue
    429     }
    430     return null;
    431   }
    432 
    433   /**
    434    * Always throws {@link UnsupportedOperationException} as removal is not supported.
    435    */
    436   public void remove() {
    437     throw new UnsupportedOperationException();
    438   }
    439 }
    440