regex – Tools for representing MongoDB regular expressions

Added in version 2.7.

Tools for representing MongoDB regular expressions.

class bson.regex.Regex(pattern, flags=0)

BSON regular expression data.

This class is useful to store and retrieve regular expressions that are incompatible with Python’s regular expression dialect.

Parameters:
  • pattern (_T) – string

  • flags (Union[str, int]) – an integer bitmask, or a string of flag characters like “im” for IGNORECASE and MULTILINE

classmethod from_native(regex)

Convert a Python regular expression into a Regex instance.

Note that in Python 3, a regular expression compiled from a str has the re.UNICODE flag set. If it is undesirable to store this flag in a BSON regular expression, unset it first:

>>> pattern = re.compile('.*')
>>> regex = Regex.from_native(pattern)
>>> regex.flags ^= re.UNICODE
>>> db.collection.insert_one({'pattern': regex})
Parameters:

regex (Pattern[_T]) – A regular expression object from re.compile().

Return type:

Regex[_T]

Warning

Python regular expressions use a different syntax and different set of flags than MongoDB, which uses PCRE. A regular expression retrieved from the server may not compile in Python, or may match a different set of strings in Python than when used in a MongoDB query.

try_compile()

Compile this Regex as a Python regular expression.

Warning

Python regular expressions use a different syntax and different set of flags than MongoDB, which uses PCRE. A regular expression retrieved from the server may not compile in Python, or may match a different set of strings in Python than when used in a MongoDB query. try_compile() may raise re.error.

Return type:

Pattern[_T]