Regex in Python

Many tool in the web help us to leverage the regex (lets list just to try live the patterns  and to learn how construct a regex).

So, what’s a regex? A regular expression, i.e., quoting

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 ) 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:


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

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 .

Leave a Reply

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