
OR or Pipe ( | ) operator –
The pipe symbol performs or operation in regex. The pattern a|b will match either a or b.
In [1]: import re
In [2]: re.findall('batman|superman', 'batman is my favorite super hero.')
Out[2]: ['batman']
In [3]: re.findall('batman|superman', 'superman is my favorite super hero.')
Out[3]: ['superman']
Here the pattern matches either batman or superman.
You can also use multiple or operations.
In [4]: re.findall('batman|superman|hulk', 'superman is my favorite super hero.')
Out[4]: ['superman']
In [5]: re.findall('batman|superman|hulk', 'batman is my favorite super hero.')
Out[5]: ['batman']
In [6]: re.findall('batman|superman|hulk', 'hulk is my favorite super hero.')
Out[6]: ['hulk']
In [7]: re.findall('batman|superman|hulk', 'hulk,batman and superman is my favorite super heroes.')
Out[7]: ['hulk', 'batman', 'superman']
How to match a Pipe Character ?
To match a pipe character, you have to escape it using a backslash.
In [8]: re.findall('\|', 'A|B')
Out[8]: ['|']