How to write a regular expression to match either a or b in Python?


The following code uses a regular expression '(a|b)' to match a or b in the given Python string.

We are also using the flag re.I to ignore case of a or b while matching.

Example

import re
s = 'Bank of Baroda'
print(re.findall(r'(a|b)',s, re.I))

Output

This gives the output

['B', 'a', 'B', 'a', 'a']

Updated on: 02-Nov-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements