Coverage for presidio_analyzer / pattern.py: 94%

32 statements  

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

1import json 

2from typing import Dict 

3 

4import regex as re 

5 

6 

7class Pattern: 

8 """ 

9 A class that represents a regex pattern. 

10 

11 :param name: the name of the pattern 

12 :param regex: the regex pattern to detect 

13 :param score: the pattern's strength (values varies 0-1) 

14 """ 

15 

16 def __init__(self, name: str, regex: str, score: float): 

17 self.name = name 

18 self.regex = regex 

19 self.score = score 

20 self.compiled_regex = None 

21 self.compiled_with_flags = None 

22 

23 self.__validate_regex(self.regex) 

24 self.__validate_score(self.score) 

25 

26 @staticmethod 

27 def __validate_regex(pattern: str) -> None: 

28 """Validate that the regex pattern is valid.""" 

29 try: 

30 re.compile(pattern) 

31 except re.error as e: 

32 raise ValueError(f"Invalid regex pattern: {e}") 

33 

34 @staticmethod 

35 def __validate_score(score: float) -> None: 

36 if score < 0 or score > 1: 

37 raise ValueError( 

38 f"Invalid score: {score}. " "Score should be between 0 and 1" 

39 ) 

40 

41 def to_dict(self) -> Dict: 

42 """ 

43 Turn this instance into a dictionary. 

44 

45 :return: a dictionary 

46 """ 

47 return_dict = {"name": self.name, "score": self.score, "regex": self.regex} 

48 return return_dict 

49 

50 @classmethod 

51 def from_dict(cls, pattern_dict: Dict) -> "Pattern": 

52 """ 

53 Load an instance from a dictionary. 

54 

55 :param pattern_dict: a dictionary holding the pattern's parameters 

56 :return: a Pattern instance 

57 """ 

58 return cls(**pattern_dict) 

59 

60 def __repr__(self): 

61 """Return string representation of instance.""" 

62 return json.dumps(self.to_dict()) 

63 

64 def __str__(self): 

65 """Return string representation of instance.""" 

66 return json.dumps(self.to_dict())