Regular Expressions: Grouping and the Pipe Character

The | character is called a pipe. We can use it anywhere we want to match one of many expressions.

Example: The regular expression r’Batman|Tina Fey’ will match either ‘Batman’ or ‘Tina Fey’. When both Batman and Tina Fey occur in the searched string, the first occurrence of matching text will be returned as the Match object.

Python3




# Python program to illustrate
# Matching regex objects
# with multiple Groups with the Pipe
import re
heroRegex = re.compile (r'Batman|Tina Fey')
mo1 = heroRegex.search('Batman and Tina Fey.')
print(mo1.group())


Output:

'Batman'

Pattern matching in Python with Regex

You may be familiar with searching for text by pressing ctrl-F and typing in the words you’re looking for. Regular expressions go one step further: They allow you to specify a pattern of text to search for. In this article, we will see how pattern matching in Python works with Regex.

Similar Reads

Regex in Python

Regular expressions, also called regex, are descriptions of a pattern of text. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. For example, a \d in a regex stands for a digit character — that is, any single numeral between 0 and 9....

Parentheses for Grouping and Capturing with Regex

...

Regular Expressions: Grouping and the Pipe Character

One of the ways of pattern matching with Regex is by using Parentheses around the patterns. Let us see a few different examples for a better understanding....

Understanding Curly Braces in Regex

...

Optional Operator or question mark (?) in Regular Expression

...

Zero or More Pattern Matching with the Star

...

One or More Pattern Matching with the Plus

The | character is called a pipe. We can use it anywhere we want to match one of many expressions....