To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

Commit 86154cec authored by vermeul's avatar vermeul
Browse files

added re.X flag recommendation

parent 3450747c
......@@ -63,4 +63,37 @@ match.groupdict()
```
</strong>
This leads to much more robust regular expressions.
\ No newline at end of file
This leads to much more robust regular expressions.
## always use re.X
**Regular expressions are not easy to fix if your intention is not clear**
The re.X flag allows you to define regular expressions over multiple lines. More importantly, it allows you to add comments to every part, so the original intention is preserved. If something is wrong with the regular expression, such a commented regular expression is much easier to debug.
Who would like to debug this regular expression?
```python
regex = re.compile('^(?P<alias_alternative>(?P<requested_entity>experiment|collection)(\.(?P<attribute>\w+))?)(\s+(?i)AS\s+(?P<alias>\w+))?\s*$)')
```
Split the regular expression on multiple lines and add comments. Of course, you need now to specify every blank space with `\s`, but this good practice anyway:
<strong>
```python
regex = re.compile(
r"""^ # beginning of the string
(?P<alias_alternative> # use first part as alias, if no alias is defined
(?P<requested_entity>sample|object) # string starts with experiment or collection
(\.(?P<attribute>\w+))? # capture an optional .attribute
)
( # capture an optional alias: entity.attribute AS alias
\s+(?i)AS\s+ # ignore case of 'AS'
(?P<alias>\w+) # capture the alias
)? #
\s* # ignore any trailing whitespace
$ # end of string
""", re.X
)
```
</strong>
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment