“Or” Logic In Regular Expression (Regex)

Boolean Logic provides different operators where “or” operator is one of them. The regular expressions are used to match specific patterns by providing characters. The “or” operator can be used to provide options to match where one of the options should match provided with the “or” operator. The “or” operator is also called as “or” logic too. In this tutorial, we examine how to use “or” logic/operator with the regular expressions (regex).

“Or” Logic Operator

The “|” is used as or logic operator. Multiple terms are provided by delimiting with the “|”. It is expected to match one of the provided terms. If one of the terms match the regular expression returns the matched part. The syntax of the “Or” logic is like below. Parenthesis is used to group terms to match as a whole.

  • TERM1, TERM2, TERM3 are character sets to match. Two or more terms can be used for a match.

“Or” Logic with Regex

Let’s make a simple example where we check if one of the provided names matches the list of names. In the following example, we use (Ahmet|John|Sandra) to match one of them.

“Or” Logic with Regex

From the output, we can see that there is a single match which is “Ahmet”. Others are not matched as they are not provided with the “Or” logic.

“Or” Logic with Python Regex

The previous “or” logic example can be implemented in the Python programming language. Python provides the “re” module for regular expression operations. So first we import the “re” module and then use the “findall()” method to match “or” logic.

import re

text = """Ahmet


Leave a Comment