@@ -456,7 +456,8 @@ class PhoneNumberMatcher(object):
456456 _DONE = 2
457457
458458 def __init__ (self , text , region ,
459- leniency = Leniency .VALID , max_tries = 65535 ):
459+ leniency = Leniency .VALID , max_tries = 65535 ,
460+ min_candidate_length = 1 ):
460461 """Creates a new instance.
461462
462463 Arguments:
@@ -471,6 +472,9 @@ def __init__(self, text, region,
471472 max_tries -- The maximum number of invalid numbers to try before
472473 giving up on the text. This is to cover degenerate cases where
473474 the text has a lot of false positives in it. Must be >= 0.
475+ min_candidate_length -- The minimum length of a candidate phone number.
476+ Can be used to quickly skip candidates that are too short to be valid,
477+ depending on your use-case needs.
474478 """
475479 if leniency is None :
476480 raise ValueError ("Need a leniency value" )
@@ -487,6 +491,8 @@ def __init__(self, text, region,
487491 self .leniency = leniency
488492 # The maximum number of retries after matching an invalid number.
489493 self ._max_tries = int (max_tries )
494+ # The minimum length of a candidate phone number.
495+ self ._min_candidate_length = int (min_candidate_length )
490496 # The iteration tristate.
491497 self ._state = PhoneNumberMatcher ._NOT_READY
492498 # The last successful match, None unless in state _READY
@@ -513,13 +519,16 @@ def _find(self, index):
513519 # 123 45 67 / 68).
514520 candidate = self ._trim_after_first_match (_SECOND_NUMBER_START_PATTERN ,
515521 candidate )
522+ candidate_len = len (candidate )
523+
524+ if candidate_len >= self ._min_candidate_length :
525+ match = self ._extract_match (candidate , start )
526+ if match is not None :
527+ return match
528+ self ._max_tries -= 1
516529
517- match = self ._extract_match (candidate , start )
518- if match is not None :
519- return match
520530 # Move along
521- index = start + len (candidate )
522- self ._max_tries -= 1
531+ index = start + candidate_len
523532 match = _PATTERN .search (self .text , index )
524533 return None
525534
0 commit comments