
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write a regular expression to match either a or b in Python?
In Python regular expressions, one of the common tasks is matching either one character or another. we can done this easily by using the re module along with the pipe symbol |, which acts as an OR operator.
In this article, we'll explore how to match either 'a' or 'b' in a string using regex. The following are the various methods included.
Using re.search() with the | symbol
The re.search() combined with the | (OR) symbol allows us to search for multiple patterns within a single string. It returns a match object if any of the patterns are found.
The | symbol acts as an "or" operator in the regular expression. It tells the re.search() method to look for any patterns separated by the | within the input string. The function stops at the first match it finds.
Example
To check if a string contains either 'a' or 'b'. We can write the regular expression as 'a|b', which means match either 'a' or 'b'.
import re text = "cat" pattern = r"a|b" result = re.search(pattern, text) if result: print("Match found:", result.group()) else: print("No match found.")
Following is the output of the above code:
Match found: a
Using re.match() for starting check
The re.match() function checks if the beginning of a string matches a pattern. If a pattern is found, it returns a match object; otherwise, it returns None.
To check whether a string starts with 'a' or 'b', we can use re.match(r"a|b", text). This entire expression checks does the string starts with either the character 'a' or 'b'.
Example
The following example demonstrates the basic usage of re.match() method to check for a match at the beginning of the string that starts with 'a' or 'b' (a|b).
import re text = "apple" pattern = r"a|b" result = re.match(pattern, text) if result: print("Starts with a or b:", result.group()) else: print("Does not start with a or b.")
Following is the output of the above code:
Starts with a or b: a
Using re.findall() for multiple matches
Another method is using re.findall()to find all the parts of a string that match a specific pattern. If we want to find all instances of 'a' or 'b' in a string, this re.findall() method will give a list containing each 'a' and each 'b' it finds. Specifically, it avoids overlapping matches. For instance, "aba" yields "a", "b", "a", not "ab" and "ba".
Example
Let's assume we want to extract all instances of 'a' or 'b' (a|b) from a string.
import re text = "banana bread" pattern = r"a|b" matches = re.findall(pattern, text) print("Matches found:", matches)
Following is the output of the above code:
Matches found: ['b', 'a', 'a', 'a', 'b', 'a']