-import re
-
-from nominatim.errors import UsageError
-from nominatim.tools import country_info
-
-class _PostcodeMatcher:
- """ Matches and formats a postcode according to the format definition.
- """
- def __init__(self, country_code, config):
- if 'pattern' not in config:
- raise UsageError("Field 'pattern' required for 'postcode' "
- f"for country '{country_code}'")
-
- pc_pattern = config['pattern'].replace('d', '[0-9]').replace('l', '[A-Z]')
-
- self.norm_pattern = re.compile(f'\\s*(?:{country_code.upper()}[ -]?)?(.*)\\s*')
- self.pattern = re.compile(pc_pattern)
-
- self.output = config.get('output', r'\g<0>')
-
-
- def match(self, postcode):
- """ Match the given postcode against the postcode pattern for this
- matcher. Returns a `re.Match` object if the match was successful
- and None otherwise.
- """
- # Upper-case, strip spaces and leading country code.
- normalized = self.norm_pattern.fullmatch(postcode.upper())
-
- if normalized:
- return self.pattern.fullmatch(normalized.group(1))
-
- return None
-
-
- def normalize(self, match):
- """ Return the default format of the postcode for the given match.
- `match` must be a `re.Match` object previously returned by
- `match()`
- """
- return match.expand(self.output)
-