Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the pattern back from a compiled re?

Tags:

Assume I have created a compiled re:

x = re.compile('^\d+$') 

Is there a way to extract the pattern string (^\d+$) back from the x?

like image 381
Bartosz Radaczyński Avatar asked Oct 10 '08 11:10

Bartosz Radaczyński


People also ask

What does it mean to compile a regex?

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. match() or re.search() .

What does re compile () do?

The re. compile() method We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.

Should I compile regex Python?

compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program. So my conclusion is, if you are going to match the same pattern for many different texts, you better precompile it.

What is the difference between re search and re match?

There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none.


1 Answers

You can get it back with

x.pattern 

from the Python documentation on Regular Expression Objects

like image 141
Bill the Lizard Avatar answered Nov 12 '22 18:11

Bill the Lizard