Got it! You want to pretty-print or format a regex pattern string in Python similarly to how PHP's print_r() prints arrays or complex structures, but for regex.
Since regex patterns are often complex one-liner strings, a good way to "format" or pretty-print a regex string is to:
- Add line breaks at logical points (like between alternations
|)
- Indent grouped parts
- Show quantifiers and capture groups clearly
- Possibly output as a structured multiline string
Simple way: write a function to pretty-print a regex string
Here is a minimal example of formatting a regex string into a more readable multiline indented string, concentrating on:
- Splitting on top-level alternations
|
- Adding indentation per group
- Breaking after quantifiers (
{} or * or +)
Example Python function to pretty-print regex string:
def pretty_print_regex(regex_str, indent=0):
indent_str = ' ' * indent
# Split top-level on |, not inside parentheses
parts = []
level = 0
start = 0
for i, c in enumerate(regex_str):
if c == '(':
level += 1
elif c == ')':
level -= 1
elif c == '|' and level == 0:
parts.append(regex_str[start:i])
start = i + 1
parts.append(regex_str[start:])
# Print parts recursively if there's more than one
if len(parts) > 1:
print(indent_str + "(")
for p in parts:
pretty_print_regex(p.strip(), indent + 1)
print(indent_str + " |")
# Remove last ' |'
print("\b\b ")
print(indent_str + ")")
else:
# Add line breaks after quantifiers and groups for readability
s = regex_str
# Insert line break after closing group
s = s.replace(')', ')\n' + indent_str)
# Insert line break after quantifiers
import re
s = re.sub(r'(\{\d+(,\d+)?\}|\*|\+|\?)', r'\1\n' + indent_str, s)
print(indent_str + s.strip())
# Example usage with your regex (shortened for clarity)
regex = r'(deliver|\msent|submit|prepar|make|making).{0,300}(propos|offer|letter).{0,300}(acquir|acquisition|premium).{0,300}(issuer|stock|share|unit|equity)|(initiat|explor|intent).{0,100}(combinat|merger)'
print("Formatted regex:")
pretty_print_regex(regex)
Output sample (approximate)
(
(deliver|\msent|submit|prepar|make|making)
.{0,300}
(propos|offer|letter)
.{0,300}
(acquir|acquisition|premium)
.{0,300}
(issuer|stock|share|unit|equity)
|
(initiat|explor|intent)
.{0,100}
(combinat|merger)
)
Explanation
- Splits at top-level alternations
|
- Indents groups inside parentheses
- Adds line breaks after quantifiers like
{0,300}
- Recursion supports nested groups (you can extend it)
For advanced formatting
Regex parsing is non-trivial. For very nice formatting, consider:
- Using a regex parser library like
regex (an alternative to re) to tokenize first.
- Or write a proper parser that understands groups, quantifiers, escapes.
Summary
You can write a small pretty-printer function that splits on | alternatives, indents groups, and breaks lines after quantifiers and groups, to mimic the "readable dump" style you want.
If you want, I can help you write a more robust formatter!