Tutorial 4: Regular Expressions in Python — Using regex metacharacters ‘ { } [ ] |’
Missed previous tutorial ? — click here
In this tutorial, we will be covering following three metacharacters :
First we will try to understand the meaning of these metacharacters and take few examples to know how to use them just as we did in previous tutorials.
1. metacharacter { }
This is used in many ways like:
{ m } where ‘m’ is an integer. It is used to match exactly ‘m’ number of copies of the regex code preceding it.
Let’s see how it works in examples
{ m, } integer ‘m’ followed by comma ( , ) .It is used to match ‘m’ or more number of copies of code preceding it.
{ m, n }where ‘m’ and ’n’ are integers. It is used to match range of ‘m’ to ’n’ number of copies of code preceding it.
2. metacharacter [ ]
This is used in many ways like:
[a-z] This indicates range of any character between ‘a’ to ‘z’. Hyphen indicates range.
[1–9] This indicates a range of integers between 1 to 9. Hyphen indicates range.
Let’s see combination of [0–9] digits and [a-z] alphabets in the example below. Also other example showing character [ ] without range. For example, [a3d8] Similar to ‘OR’ operator, this matches with any of the characters ‘a’ or ‘3’ or ‘d’ or ‘8’. You can specify any characters to match. DO NOT use comma between them.
3. metacharacter ‘|’
This works like ‘OR’ operator. For example, A|B matches with ‘A’ or ‘B’ and (1|c|f|4) matches with 1 or ‘c’ or ‘f’ or 4 .
Let’s understand this using examples :
To compare ( | ) and [ ] :
By now, we have covered a lot important topics used in regex in only four tutorials. More fun is yet to come. Stay tuned !!
Take a deep breathe and move to the next tutorial.
Happy learning !!!