BSON regular expression data.
| 44 | |
| 45 | |
| 46 | class Regex(Generic[_T]): |
| 47 | """BSON regular expression data.""" |
| 48 | |
| 49 | __slots__ = ("pattern", "flags") |
| 50 | |
| 51 | __getstate__ = _getstate_slots |
| 52 | __setstate__ = _setstate_slots |
| 53 | |
| 54 | _type_marker = 11 |
| 55 | |
| 56 | @classmethod |
| 57 | def from_native(cls: Type[Regex[Any]], regex: Pattern[_T]) -> Regex[_T]: |
| 58 | """Convert a Python regular expression into a ``Regex`` instance. |
| 59 | |
| 60 | Note that in Python 3, a regular expression compiled from a |
| 61 | :class:`str` has the ``re.UNICODE`` flag set. If it is undesirable |
| 62 | to store this flag in a BSON regular expression, unset it first:: |
| 63 | |
| 64 | >>> pattern = re.compile('.*') |
| 65 | >>> regex = Regex.from_native(pattern) |
| 66 | >>> regex.flags ^= re.UNICODE |
| 67 | >>> db.collection.insert_one({'pattern': regex}) |
| 68 | |
| 69 | :param regex: A regular expression object from ``re.compile()``. |
| 70 | |
| 71 | .. warning:: |
| 72 | Python regular expressions use a different syntax and different |
| 73 | set of flags than MongoDB, which uses `PCRE`_. A regular |
| 74 | expression retrieved from the server may not compile in |
| 75 | Python, or may match a different set of strings in Python than |
| 76 | when used in a MongoDB query. |
| 77 | |
| 78 | .. _PCRE: http://www.pcre.org/ |
| 79 | """ |
| 80 | if not isinstance(regex, RE_TYPE): |
| 81 | raise TypeError("regex must be a compiled regular expression, not %s" % type(regex)) |
| 82 | |
| 83 | return Regex(regex.pattern, regex.flags) |
| 84 | |
| 85 | def __init__(self, pattern: _T, flags: Union[str, int] = 0) -> None: |
| 86 | """BSON regular expression data. |
| 87 | |
| 88 | This class is useful to store and retrieve regular expressions that are |
| 89 | incompatible with Python's regular expression dialect. |
| 90 | |
| 91 | :param pattern: string |
| 92 | :param flags: an integer bitmask, or a string of flag |
| 93 | characters like "im" for IGNORECASE and MULTILINE |
| 94 | """ |
| 95 | if not isinstance(pattern, (str, bytes)): |
| 96 | raise TypeError("pattern must be a string, not %s" % type(pattern)) |
| 97 | self.pattern: _T = pattern |
| 98 | |
| 99 | if isinstance(flags, str): |
| 100 | self.flags = str_flags_to_int(flags) |
| 101 | elif isinstance(flags, int): |
| 102 | self.flags = flags |
| 103 | else: |
no outgoing calls