NBRegExMatcher.m 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // NBRegExMatcher.m
  3. // libPhoneNumber
  4. //
  5. // Created by Paween Itthipalkul on 11/29/17.
  6. // Copyright © 2017 Google LLC. All rights reserved.
  7. //
  8. #import "NBRegExMatcher.h"
  9. #import "NBPhoneNumberDesc.h"
  10. #import "NBRegularExpressionCache.h"
  11. #import "NBPhoneNumberUtil.h"
  12. // Expose this method to get a modified RegEx to cover the entire RegEx.
  13. // Though all RegEx methods and functionalities should be moved to either this class, or a separate
  14. // class rather than in NBPhoneNumberUtil.
  15. @interface NBPhoneNumberUtil()
  16. - (NSRegularExpression *)entireRegularExpressionWithPattern:(NSString *)regexPattern
  17. options:(NSRegularExpressionOptions)options
  18. error:(NSError **)error;
  19. @end
  20. @implementation NBRegExMatcher
  21. - (BOOL)matchNationalNumber:(NSString *)string
  22. phoneNumberDesc:(NBPhoneNumberDesc *)numberDesc
  23. allowsPrefixMatch:(BOOL)allowsPrefixMatch {
  24. NSString *nationalNumberPattern = numberDesc.nationalNumberPattern;
  25. // We don't want to consider it a prefix match when matching non-empty input against an empty
  26. // pattern.
  27. if (nationalNumberPattern.length == 0) {
  28. return NO;
  29. }
  30. NSRegularExpression *regEx =
  31. [[NBPhoneNumberUtil sharedInstance] entireRegularExpressionWithPattern:nationalNumberPattern
  32. options:kNilOptions
  33. error:nil];
  34. if (regEx == nil) {
  35. NSAssert(true, @"Regular expression shouldn't be nil");
  36. return NO;
  37. }
  38. NSRange wholeStringRange = NSMakeRange(0, string.length);
  39. // Prefix match (lookingAt()) search
  40. NSRegularExpression *prefixRegEx =
  41. [[NBRegularExpressionCache sharedInstance] regularExpressionForPattern:nationalNumberPattern
  42. error:NULL];
  43. if (prefixRegEx == nil) {
  44. NSAssert(true, @"Regular expression shouldn't be nil");
  45. return NO;
  46. }
  47. NSTextCheckingResult *prefixResult = [prefixRegEx firstMatchInString:string
  48. options:NSMatchingAnchored
  49. range:wholeStringRange];
  50. if (prefixResult.numberOfRanges <= 0) {
  51. // No prefix match found.
  52. return NO;
  53. } else {
  54. // Found prefix match, but need to see if exact match works as well.
  55. // Exact match (matches()) search.
  56. NSTextCheckingResult *exactResult = [regEx firstMatchInString:string
  57. options:NSMatchingAnchored
  58. range:wholeStringRange];
  59. return (allowsPrefixMatch || exactResult.numberOfRanges > 0);
  60. }
  61. }
  62. @end