Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Python Regular Expressions

You're reading from  Mastering Python Regular Expressions

Product type Book
Published in Feb 2014
Publisher Packt
ISBN-13 9781783283156
Pages 110 pages
Edition 1st Edition
Languages

Special cases with groups


Python provides us with some forms of groups that can help us to modify the regular expressions or even to match a pattern only when a previous group exists in the match, such as an if statement.

Flags per group

There is a way to apply the flags we've seen in Chapter 2 Regular Expressions with Python, using a special form of grouping: (?iLmsux).

Letter

Flag

i

re.IGNORECASE

L

re.LOCALE

m

re.MULTILINE

s

re.DOTALL

u

re.UNICODE

x

re.VERBOSE

For example:

>>>re.findall(r"(?u)\w+" ,ur"ñ")
[u'\xf1']

The above example is the same as:

>>>re.findall(r"\w+" ,ur"ñ", re.U)
[u'\xf1']

We've seen what these examples do several times in the previous chapter.

Remember that a flag is applied to the whole expression.

yes-pattern|no-pattern

This is a very useful case of groups. It tries to match a pattern in case a previous one was found. On the other hand, it doesn't try to match a pattern in case a previous group was not found. In short, it's like an if-else statement...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}