OR Operator in re Module

Regular Expressions Mar 20, 2026

OR Operator in re Module

The OR operator (|) in Python’s re module lets you match one pattern OR another in a single regular expression. It is one of the most useful metacharacters for data science tasks such as extracting multiple log levels, detecting different date formats, validating multiple ID types, or cleaning inconsistent text. Mastering | (with proper grouping) makes your regex patterns concise, flexible, and production-ready.

TL;DR — OR Operator

  • pattern1|pattern2 → matches either pattern1 or pattern2
  • Use parentheses for grouping: (error|warning|info)
  • Non-capturing group for speed: (?:error|warning|info)
  • Works perfectly with pandas .str.extract() and .str.replace()

1. Basic OR Operator

import re

text = "ERROR: system crash\nWARNING: low memory\nINFO: user logged in"

# Simple OR
levels = re.findall(r"ERROR|WARNING|INFO", text)
print(levels)

# Grouped OR (capturing)
levels = re.findall(r"(ERROR|WARNING|INFO)", text)
print(levels)

2. Real-World Data Science Examples with Pandas

import pandas as pd

# Demo file so this example runs as-is (in your project this is your real log export)
pd.DataFrame({"log": [
    "2026-03-19 ERROR: Payment failed for ORD-12345 amount $1,250.75 Qty: 3 user alice@example.com!!! https://shop.example.com/o/12345 call +1 555-123-4567",
    "2026-03-19 WARNING: Slow response for ORD-98765 amount $87.50 Qty: 1 bob@company.com on 03/19/2026 aaaa",
    "INFO: user logged in ORD-555 amount $12.00 Qty: 2 carol@data.org <b>ok</b>",
]}).to_csv("logs.csv", index=False)

df = pd.read_csv("logs.csv")

# Example 1: Extract any log level
df["level"] = df["log"].str.extract(r"(ERROR|WARNING|INFO|DEBUG)", flags=re.IGNORECASE)

# Example 2: Match multiple date formats in one go
df["date"] = df["log"].str.extract(r"(\d{4}-\d{2}-\d{2}|\d{2}/\d{2}/\d{4})")

# Example 3: Replace multiple unwanted patterns
df["clean"] = df["log"].str.replace(r"(ERROR|WARNING|INFO):", "[LOG]", regex=True)

3. Advanced OR with Non-Capturing Groups

# Non-capturing OR (cleaner match object)
pattern = re.compile(r"(?:ERROR|WARNING|INFO):\s*(.+)", re.IGNORECASE)

match = pattern.search("warning: disk full")
print(match.group(1) if match else None)

4. Best Practices in 2026

  • Always wrap OR in parentheses when combined with other parts of the pattern
  • Use non-capturing groups (?:...) when you don’t need the captured value
  • Combine with re.IGNORECASE for case-insensitive matching
  • Place the most specific pattern first in OR lists (regex tries left-to-right)
  • Use pandas vectorized methods with regex=True for large DataFrames

How Python Chooses Between Alternatives

Python's regex engine tries alternatives from left to right and takes the first one that matches at the current position. It does not look for the longest alternative. So cat|category matches only "cat" in "category".

Put longer or more specific alternatives first, or add word boundaries such as \b(cat|category)\b so a short alternative cannot match part of a word.

Alternation has very low precedence: ^a|b$ means "^a" or "b$", not "^(a|b)$". Wrap alternatives in a group when combining them with other parts.

Worked Example: Alternative Order and Grouping

We compare different orders and groupings of the same alternatives.

import re

text = "category cat"
print(re.findall(r"cat|category", text))
print(re.findall(r"category|cat", text))
print(re.findall(r"\b(?:cat|category)\b", text))

print(bool(re.fullmatch(r"jpg|png", "png")), bool(re.search(r"^img\.jpg|png$", "img.gif.png")))

The first pattern returns "cat" twice because the short alternative wins. Reordering or using word boundaries finds both words correctly. The last line shows how ^ and $ attach to only one alternative without a group.

Practical Tips

When alternatives share a prefix, such as cat and category, either sort them longest first or factor the prefix out, as in cat(?:egory)?. The factored version is shorter and makes the intent clear.

Test alternations on text where several alternatives could match at the same position, because that is where order matters.

Print the matched text, not just True or False, so you can see which alternative won.

Group alternatives whenever anchors or quantifiers sit next to them.

Common Mistakes

  • Putting a short alternative before a longer one.
  • Forgetting a group around alternatives combined with anchors.
  • Expecting the engine to choose the longest match.
  • Using alternation for single characters instead of a class.

Quick Summary

  • Alternatives are tried left to right.
  • The first match wins, not the longest.
  • Group alternatives with anchors.
  • Word boundaries prevent partial matches.

Conclusion

The OR operator (|) in the re module is a simple yet extremely powerful tool for handling multiple alternatives in one pattern. In 2026 data science projects, using grouped OR with non-capturing syntax lets you write clean, fast, and maintainable regex for log parsing, multi-format extraction, and data standardization. Combined with pandas, it scales effortlessly across massive text datasets.

Next steps:

  • Find a place in your current code where you run multiple separate regex searches and replace them with a single OR operator

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices