• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 #include "phonenumbers/regex_based_matcher.h"
18 
19 #include <string>
20 
21 #include "phonenumbers/base/memory/scoped_ptr.h"
22 #include "phonenumbers/phonemetadata.pb.h"
23 #include "phonenumbers/regexp_adapter.h"
24 #include "phonenumbers/regexp_cache.h"
25 #include "phonenumbers/regexp_factory.h"
26 
27 namespace i18n {
28 namespace phonenumbers {
29 
30 // Same implementations of AbstractRegExpFactory and RegExpCache in
31 // PhoneNumberUtil (copy from phonenumberutil.cc).
RegexBasedMatcher()32 RegexBasedMatcher::RegexBasedMatcher()
33     : regexp_factory_(new RegExpFactory()),
34       regexp_cache_(new RegExpCache(*regexp_factory_, 128)) {}
35 
~RegexBasedMatcher()36 RegexBasedMatcher::~RegexBasedMatcher() {}
37 
MatchNationalNumber(const string & number,const PhoneNumberDesc & number_desc,bool allow_prefix_match) const38 bool RegexBasedMatcher::MatchNationalNumber(
39     const string& number,
40     const PhoneNumberDesc& number_desc,
41     bool allow_prefix_match) const {
42   const string& national_number_pattern = number_desc.national_number_pattern();
43   // We don't want to consider it a prefix match when matching non-empty input
44   // against an empty pattern.
45   if (national_number_pattern.empty()) {
46     return false;
47   }
48   return Match(number, national_number_pattern, allow_prefix_match);
49 }
50 
Match(const string & number,const string & number_pattern,bool allow_prefix_match) const51 bool RegexBasedMatcher::Match(
52     const string& number,
53     const string& number_pattern,
54     bool allow_prefix_match) const {
55   const RegExp& regexp(regexp_cache_->GetRegExp(number_pattern));
56 
57   if (regexp.FullMatch(number)) {
58     return true;
59   }
60   const scoped_ptr<RegExpInput> normalized_number_input(
61       regexp_factory_->CreateInput(number));
62   return regexp.Consume(normalized_number_input.get())
63       ? allow_prefix_match
64       : false;
65 }
66 
67 }  // namespace phonenumbers
68 }  // namespace i18n
69