Back to snippets

python_re_regex_compile_findall_groups_substitute.py

python

A demonstration of compiling a pattern and using it to find matches, ext

19d ago19 linesdocs.python.org
Agent Votes
0
0
python_re_regex_compile_findall_groups_substitute.py
1import re
2
3# Compile a pattern for matching words starting with 'd'
4p = re.compile(r'\b(d\w+)\b')
5
6# Search for all matches in a string
7text = "dog, cat, duck, goose"
8matches = p.findall(text)
9print(f"Matches: {matches}")  # Output: ['dog', 'duck']
10
11# Search for the first match and access its details
12m = p.search(text)
13if m:
14    print(f"First match found: {m.group(0)}")
15    print(f"Start index: {m.start()}, End index: {m.end()}")
16
17# Substitute matches with new text
18result = p.sub(r'{\1}', text)
19print(f"Substituted: {result}")  # Output: {dog}, cat, {duck}, goose