What is the type of the compiled regular expression in python?
In particular, I want to evaluate
isinstance(re.compile(''), ???)
to be true, for introspection purposes.
One solution I had was, have some global constant REGEX_TYPE = type(re.compile(''))
, but it doesn't seem very elegant.
EDIT: The reason I want to do this is because I have list of strings and compiled regex objects. I want to "match" a string against list, by
and the code that I came up with was:
for allowed in alloweds: if isinstance(allowed, basestring) and allowed == input: ignored = False break elif isinstance(allowed, REGEX_TYPE) and allowed.match(input): ignored = False break
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The Python module re provides full support for Perl-like regular expressions in Python.
Python's re. compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.
There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression.
If a Regex object is constructed with the RegexOptions. Compiled option, it compiles the regular expression to explicit MSIL code instead of high-level regular expression internal instructions. This allows .
Python 3.5 introduced the typing
module. Included therein is typing.Pattern
, a _TypeAlias
.
Starting with Python 3.6, you can simply do:
from typing import Pattern my_re = re.compile('foo') assert isinstance(my_re, Pattern)
In 3.5, there used to be a bug requiring you to do this:
assert issubclass(type(my_re), Pattern)
Which isn’t guaranteed to work according to the documentation and test suite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With