Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of compiled regex object in python

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

  • for each string in the list, try to check for string equality.
  • for each regex in the list, try to check whether the string matches the given pattern.

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 
like image 893
Jeeyoung Kim Avatar asked May 23 '11 19:05

Jeeyoung Kim


People also ask

What type of regex does Python use?

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.

What is Python regex compile?

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.

How many types of regex are there?

There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression.

What is regex compilation?

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 .


1 Answers

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.

like image 133
flying sheep Avatar answered Oct 17 '22 01:10

flying sheep