1. import re
  2. def match_query_pattern(query, patterns):
  3. """
  4. Matches a query string against a list of patterns, with fallback logic.
  5. Args:
  6. query (str): The query string to match.
  7. patterns (list of tuples): A list of (pattern, value) tuples.
  8. Pattern is a regex string.
  9. Returns:
  10. str: The matched value if a pattern matches, otherwise None.
  11. """
  12. for pattern, value in patterns:
  13. match = re.search(pattern, query) # Search for the pattern in the query
  14. if match:
  15. return value # Return the value if a match is found
  16. return None # Return None if no pattern matches
  17. if __name__ == '__main__':
  18. # Example Usage
  19. patterns = [
  20. (r"color=(.*)", "color"), # Matches "color=..." and returns "color"
  21. (r"size=(.*)", "size"), # Matches "size=..." and returns "size"
  22. (r"price=(\d+\.?\d*)", "price"), # Matches "price=..." and returns "price"
  23. (r"category=(.*)", "category"), # Matches "category=..." and returns "category"
  24. (r"discount=(.*)", "discount") # Matches "discount=..." and returns "discount"
  25. ]
  26. query1 = "color=red&size=large"
  27. query2 = "price=25.99"
  28. query3 = "category=electronics&discount=10%"
  29. query4 = "someotherparam=value"
  30. query5 = "size=small&color=blue"
  31. query6 = "invalid_param=value"
  32. print(f"Query: {query1}, Match: {match_query_pattern(query1, patterns)}")
  33. print(f"Query: {query2}, Match: {match_query_pattern(query2, patterns)}")
  34. print(f"Query: {query3}, Match: {match_query_pattern(query3, patterns)}")
  35. print(f"Query: {query4}, Match: {match_query_pattern(query4, patterns)}")
  36. print(f"Query: {query5}, Match: {match_query_pattern(query5, patterns)}")
  37. print(f"Query: {query6}, Match: {match_query_pattern(query6, patterns)}")

Add your comment