Member-only story

🔍 Day 54 of #100DaysOfCode in Python: Advancing Regex Skills

Elshad Karimov
2 min readJan 16, 2024

Welcome to Day 54! Today, we’re continuing our journey with regular expressions (regex) in Python, focusing on capturing groups, lookaheads, and lookbehinds. These advanced regex features allow for more precise text pattern manipulation and extraction.

1. Capturing Groups

  • Purpose: Capture parts of the matching text, which can be extracted or manipulated.
  • Syntax: Use parentheses () to create a group.
import re
pattern = r"(ab)(cd)"
match = re.search(pattern, "abcdef")
# match.group(1) is 'ab', match.group(2) is 'cd'

2. Non-Capturing Groups

  • Usage: Group part of a regex pattern without capturing it.
  • Syntax: ?: at the start of the group.
pattern = r"(?:ab)cd"

3. Named Groups

  • Benefit: Assign names to groups for better readability.
  • Syntax: (?P<name>...).
pattern = r"(?P<first>ab)(?P<second>cd)"
match = re.search(pattern, "abcdef")
# match.group('first') is 'ab'

4. Lookahead Assertions

  • Purpose: Match a group of characters only if followed by another group (positive…

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet