regex.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # Copyright 2013-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tools for representing MongoDB regular expressions.
  15. """
  16. import re
  17. from bson.son import RE_TYPE
  18. from bson.py3compat import string_type, text_type
  19. def str_flags_to_int(str_flags):
  20. flags = 0
  21. if "i" in str_flags:
  22. flags |= re.IGNORECASE
  23. if "l" in str_flags:
  24. flags |= re.LOCALE
  25. if "m" in str_flags:
  26. flags |= re.MULTILINE
  27. if "s" in str_flags:
  28. flags |= re.DOTALL
  29. if "u" in str_flags:
  30. flags |= re.UNICODE
  31. if "x" in str_flags:
  32. flags |= re.VERBOSE
  33. return flags
  34. class Regex(object):
  35. """BSON regular expression data."""
  36. _type_marker = 11
  37. @classmethod
  38. def from_native(cls, regex):
  39. """Convert a Python regular expression into a ``Regex`` instance.
  40. Note that in Python 3, a regular expression compiled from a
  41. :class:`str` has the ``re.UNICODE`` flag set. If it is undesirable
  42. to store this flag in a BSON regular expression, unset it first::
  43. >>> pattern = re.compile('.*')
  44. >>> regex = Regex.from_native(pattern)
  45. >>> regex.flags ^= re.UNICODE
  46. >>> db.collection.insert({'pattern': regex})
  47. :Parameters:
  48. - `regex`: A regular expression object from ``re.compile()``.
  49. .. warning::
  50. Python regular expressions use a different syntax and different
  51. set of flags than MongoDB, which uses `PCRE`_. A regular
  52. expression retrieved from the server may not compile in
  53. Python, or may match a different set of strings in Python than
  54. when used in a MongoDB query.
  55. .. _PCRE: http://www.pcre.org/
  56. """
  57. if not isinstance(regex, RE_TYPE):
  58. raise TypeError(
  59. "regex must be a compiled regular expression, not %s"
  60. % type(regex))
  61. return Regex(regex.pattern, regex.flags)
  62. def __init__(self, pattern, flags=0):
  63. """BSON regular expression data.
  64. This class is useful to store and retrieve regular expressions that are
  65. incompatible with Python's regular expression dialect.
  66. :Parameters:
  67. - `pattern`: string
  68. - `flags`: (optional) an integer bitmask, or a string of flag
  69. characters like "im" for IGNORECASE and MULTILINE
  70. """
  71. if not isinstance(pattern, (text_type, bytes)):
  72. raise TypeError("pattern must be a string, not %s" % type(pattern))
  73. self.pattern = pattern
  74. if isinstance(flags, string_type):
  75. self.flags = str_flags_to_int(flags)
  76. elif isinstance(flags, int):
  77. self.flags = flags
  78. else:
  79. raise TypeError(
  80. "flags must be a string or int, not %s" % type(flags))
  81. def __eq__(self, other):
  82. if isinstance(other, Regex):
  83. return self.pattern == other.pattern and self.flags == other.flags
  84. else:
  85. return NotImplemented
  86. __hash__ = None
  87. def __ne__(self, other):
  88. return not self == other
  89. def __repr__(self):
  90. return "Regex(%r, %r)" % (self.pattern, self.flags)
  91. def try_compile(self):
  92. """Compile this :class:`Regex` as a Python regular expression.
  93. .. warning::
  94. Python regular expressions use a different syntax and different
  95. set of flags than MongoDB, which uses `PCRE`_. A regular
  96. expression retrieved from the server may not compile in
  97. Python, or may match a different set of strings in Python than
  98. when used in a MongoDB query. :meth:`try_compile()` may raise
  99. :exc:`re.error`.
  100. .. _PCRE: http://www.pcre.org/
  101. """
  102. return re.compile(self.pattern, self.flags)