re_util.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import re
  2. def search_string(pattern: str, text: str) -> re.Match[str] | None:
  3. """
  4. 全字段正则匹配
  5. 参数:
  6. - pattern (str): 正则表达式模式。
  7. - text (str): 待匹配的文本。
  8. 返回:
  9. - re.Match[str] | None: 匹配结果。
  10. """
  11. if not pattern or not text:
  12. return None
  13. result = re.search(pattern, text)
  14. return result
  15. def match_string(pattern: str, text: str) -> re.Match[str] | None:
  16. """
  17. 从字段开头正则匹配
  18. 参数:
  19. - pattern (str): 正则表达式模式。
  20. - text (str): 待匹配的文本。
  21. 返回:
  22. - re.Match[str] | None: 匹配结果。
  23. """
  24. if not pattern or not text:
  25. return None
  26. result = re.match(pattern, text)
  27. return result
  28. def is_phone(number: str) -> re.Match[str] | None:
  29. """
  30. 检查手机号码格式
  31. 参数:
  32. - number (str): 待检查的手机号码。
  33. 返回:
  34. - re.Match[str] | None: 匹配结果。
  35. """
  36. if not number:
  37. return None
  38. phone_pattern = r"^1[3-9]\d{9}$"
  39. return match_string(phone_pattern, number)
  40. def is_git_url(url: str) -> re.Match[str] | None:
  41. """
  42. 检查 git URL 格式
  43. 参数:
  44. - url (str): 待检查的 URL。
  45. 返回:
  46. - re.Match[str] | None: 匹配结果。
  47. """
  48. if not url:
  49. return None
  50. git_pattern = r"^(?!(git\+ssh|ssh)://|git@)(?P<scheme>git|https?|file)://(?P<host>[^/]*)(?P<path>(?:/[^/]*)*/)(?P<repo>[^/]+?)(?:\.git)?$"
  51. return match_string(git_pattern, url)