Regex in Python

Many tool in the web help us to leverage the regex (lets list just https://regex101.com/ to try live the patterns  and http://rexegg.com/ to learn how construct a regex).

So, what’s a regex? A regular expression, i.e., quoting http://rexegg.com/:

A regex is a text string that describes a pattern that a regex engine uses in order to find text (or positions) in a body of text, typically for the purposes of validating, finding, replacing or splitting.

But what if you need a python regex?
Then you pass trough the re module (and import re line https://docs.python.org/3/library/re.html ) and special objects (in Python everything is an object), like  Match object .

Methods or attributes of a Match object are:

.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match

To fast refer to the example, you can access this page:  https://code.sololearn.com/c7P2n5x2CmYO

 

1. Greedy and Lazy Matching

The ? symbol, inside of a pattern, can mean many things. One of these is “have a lazy behavior”.

Id est, consider this example:

 

txt = “The pain in Train. The man in Black#2 Spain”
print(re.findall(“(?i)^.+?\s”, txt)) # [‘The ‘]
# Lazy behavior: you can “read” the regex .+?\s like: use .+ till the very firs space
print(re.findall(“(?i)^.+\s”, txt)) # [‘The pain in Train. The man in Black#2 ‘]
# notice without: almost all string is covered. it stops just al last space \s

 

Have a look to

https://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions

2. re.findall

The method findall is the “simplest” for us. Do you search the regex to find something? Well, re.findall(pattern, string) returns you a list with this something.

 

 

3. search() Function

The search() function searches the string for a match, and returns

If you’re a fan of list comprehension. have a look here https://stackoverflow.com/questions/2436607/how-to-use-re-match-objects-in-a-list-comprehension .

Leave a Reply

Your email address will not be published. Required fields are marked *