Coverage for presidio_analyzer / predefined_recognizers / country_specific / uk / uk_postcode_recognizer.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-03-29 09:03 +0000

1from typing import List, Optional 

2 

3from presidio_analyzer import Pattern, PatternRecognizer 

4 

5 

6class UkPostcodeRecognizer(PatternRecognizer): 

7 """ 

8 Recognizes UK postcodes using regex. 

9 

10 UK postcodes follow strict position-specific letter rules across 

11 six formats (A9 9AA, A99 9AA, A9A 9AA, AA9 9AA, AA99 9AA, AA9A 9AA) 

12 plus the special GIR 0AA code. 

13 

14 Reference: https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom 

15 

16 :param patterns: List of patterns to be used by this recognizer 

17 :param context: List of context words to increase confidence in detection 

18 :param supported_language: Language this recognizer supports 

19 :param supported_entity: The entity this recognizer can detect 

20 """ 

21 

22 PATTERNS = [ 

23 Pattern( 

24 "UK Postcode", 

25 r"\b(" 

26 r"GIR\s?0AA" 

27 r"|[A-PR-UWYZ][0-9][ABCDEFGHJKPSTUW]?\s?[0-9][ABD-HJLNP-UW-Z]{2}" 

28 r"|[A-PR-UWYZ][0-9]{2}\s?[0-9][ABD-HJLNP-UW-Z]{2}" 

29 r"|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]?\s?[0-9][ABD-HJLNP-UW-Z]{2}" 

30 r"|[A-PR-UWYZ][A-HK-Y][0-9]{2}\s?[0-9][ABD-HJLNP-UW-Z]{2}" 

31 r")\b", 

32 0.1, 

33 ), 

34 ] 

35 

36 CONTEXT = [ 

37 "postcode", 

38 "post code", 

39 "postal code", 

40 "zip", 

41 "address", 

42 "delivery", 

43 "mailing", 

44 "shipping", 

45 "correspondence", 

46 ] 

47 

48 def __init__( 

49 self, 

50 patterns: Optional[List[Pattern]] = None, 

51 context: Optional[List[str]] = None, 

52 supported_language: str = "en", 

53 supported_entity: str = "UK_POSTCODE", 

54 name: Optional[str] = None, 

55 ): 

56 patterns = patterns if patterns else self.PATTERNS 

57 context = context if context else self.CONTEXT 

58 super().__init__( 

59 supported_entity=supported_entity, 

60 patterns=patterns, 

61 context=context, 

62 supported_language=supported_language, 

63 name=name, 

64 )