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...