1. import json
  2. import re
  3. def match_json_pattern(json_string, patterns):
  4. """
  5. Matches a JSON string against a list of regular expression patterns.
  6. Args:
  7. json_string (str): The JSON string to match.
  8. patterns (dict): A dictionary where keys are pattern names and values are regular expression strings.
  9. Returns:
  10. dict: A dictionary containing the matched pattern names and their corresponding matches.
  11. Returns an empty dictionary if no patterns match.
  12. """
  13. matches = {}
  14. try:
  15. data = json.loads(json_string) # Parse the JSON string
  16. except json.JSONDecodeError:
  17. return {} # Return empty dict if JSON is invalid
  18. for pattern_name, pattern in patterns.items():
  19. try:
  20. match = re.search(pattern, json_string, re.DOTALL) # Search for the pattern
  21. if match:
  22. matches[pattern_name] = match.group(0) # Store the matched string
  23. except re.error as e:
  24. print(f"Invalid regex pattern '{pattern_name}': {e}") #Report invalid regex patterns
  25. return matches
  26. if __name__ == '__main__':
  27. # Example usage
  28. patterns = {
  29. "error_message": r'"error": "(.*)"', # Matches JSON with an "error" field containing a string
  30. "status_code": r'"status": (\d+)', # Matches JSON with a "status" field containing a number
  31. "user_id": r'"user_id": (\d+)' #Matches JSON with a user_id field containing a number
  32. }
  33. # Test JSON strings
  34. json_strings = [
  35. '{"error": "Invalid input"}',
  36. '{"status": 200}',
  37. '{"user_id": 123}',
  38. '{"message": "Success"}',
  39. '{"status": "success"}' #This will not match status_code
  40. ]
  41. for json_string in json_strings:
  42. matched_patterns = match_json_pattern(json_string, patterns)
  43. print(f"JSON: {json_string}")
  44. print(f"Matched Patterns: {matched_patterns}")
  45. print("-" * 20)

Add your comment