Convert a Python regular expression into a ``Regex`` instance. Note that in Python 3, a regular expression compiled from a :class:`str` has the ``re.UNICODE`` flag set. If it is undesirable to store this flag in a BSON regular expression, unset it first:: >>> patt
(cls: Type[Regex[Any]], regex: Pattern[_T])
| 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. |