GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python Match.string - Accessing Original String in Regex Matches Python Match.string Attributelast modified April 20, 2025 Introduction to Match.string
The This attribute is read-only and provides access to the complete input string, not just the matched portion. It's useful for context operations around matches.
Match objects are returned by Basic Syntax
The syntax for accessing match.string
Where Basic Match.string Usage
Let's start with a simple example demonstrating basic basic_string.py
#!/usr/bin/python
import re
text = "The quick brown fox jumps over the lazy dog"
match = re.search(r'fox', text)
if match:
print("Matched text:", match.group())
print("Original string:", match.string)
print("Is same object?", match.string is text)
This example shows how to access the original string from a match object.
The output confirms it's the same string object passed to match = re.search(r'fox', text) We perform a basic regex search that looks for the word 'fox' in our text. This returns a match object if successful. print("Original string:", match.string)
The Using Match.string with Multiple Matches
The multiple_matches.py
#!/usr/bin/python
import re
text = "apple orange apple banana apple"
pattern = re.compile(r'apple')
for match in pattern.finditer(text):
print(f"Found '{match.group()}' at {match.start()}-{match.end()}")
print("Full string:", match.string)
print("---")
This demonstrates that each match object references the same original string.
The Context Extraction with Match.string
We can use context_extraction.py
#!/usr/bin/python
import re
text = "The event will occur on 2023-12-25 at 14:30"
match = re.search(r'\d{4}-\d{2}-\d{2}', text)
if match:
start, end = match.start(), match.end()
context = match.string[max(0, start-10):end+10]
print(f"Found date: {match.group()}")
print(f"Context: ...{context}...")
This shows how to use the original string to get text around the match.
The Match.string with Compiled Patterns
The compiled_pattern.py
#!/usr/bin/python import re text = "User: john_doe, Email: [email protected]" pattern = re.compile(r'(\w+)@(\w+\.\w+)') match = pattern.search(text) if match: print("Full match:", match.group()) print("Original string:", match.string) print("Username:", match.group(1)) print("Domain:", match.group(2))
Compiled patterns produce match objects with the same String Verification with Match.string
We can verify if a match came from a specific string using string_verification.py
#!/usr/bin/python
import re
original = "Important message: SECRET123"
copy_text = original[:]
match = re.search(r'SECRET\d+', original)
if match:
print("Is original string?", match.string is original)
print("Is copy string?", match.string is copy_text)
print("Content equal?", match.string == copy_text)
This demonstrates that Match.string in Replacement Functions
The replacement_callback.py
#!/usr/bin/python
import re
text = "Prices: $10, $20, $30"
def add_tax(match):
price = int(match.group(1))
taxed = price * 1.2
return f"${taxed:.2f} (original: {match.string[match.start():match.end()]})"
result = re.sub(r'\$(\d+)', add_tax, text)
print(result)
The replacement function uses Match.string with Multiline StringsThe attribute preserves the complete string, including newlines. multiline_string.py
#!/usr/bin/python
import re
text = """First line
Second line with IMPORTANT data
Third line"""
match = re.search(r'IMPORTANT', text)
if match:
print("Matched:", match.group())
print("Complete string:", repr(match.string))
line_start = match.string.rfind('\n', 0, match.start()) + 1
line_end = match.string.find('\n', match.end())
print("Full line:", match.string[line_start:line_end])
This shows how to use Best Practices
When using
Performance Considerations
The However, keeping match objects alive will keep the original string in memory. For large strings, consider extracting needed portions and discarding matches. SourcePython Match Objects documentation
This tutorial covered the essential aspects of Python's AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |