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 f373ca0f authored by vermeul's avatar vermeul
Browse files

Update 12-Regular_Expressions.md

parent c4c9b5a3
......@@ -96,4 +96,32 @@ regex = re.compile(
""", re.X
)
```
</strong>
\ No newline at end of file
</strong>
## `re.split` – split string with a regular expression
The example above can be rewritten by using the traditional `strip()` function to remove leading and trailing spaces, and the `re.split` function to separate attribute and alias:
```
input_string = input_string.strip()
attribute, alias = re.split(r'\s+AS\s+', input_string, flags=re.IGNORECASE)
```
However, if no alias was defined, this will throw the following error:
```
ValueError: not enough values to unpack (expected 2, got 1)
```
This is very unfortunate, as we often encounter real-life problems, where a split might only return one value instead of two. To solve this, you can use this trick:
<strong>
```
input_string = input_string.strip()
attribute, *alias = re.split(r'\s+AS\s+', input_string, flags=re.IGNORECASE)
alias = alias[0] if alias else attribute
```
</strong>
In this case, our alias will be the same as the attribute, if it was not explicitly defined.
\ 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