-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 normalize(self, postcode):
- """ Return the normalized version of the postcode. If the given postcode
- does not correspond to the usage-pattern, return null.
- """
- # Upper-case, strip spaces and leading country code.
- normalized = self.norm_pattern.fullmatch(postcode.upper())
-
- if normalized:
- match = self.pattern.fullmatch(normalized.group(1))
- return match.expand(self.output) if match else None
-
- return None