Common Regular Expression Metacharacters and Their Usage in Python
This article explains the most frequently used regular expression symbols in Python, covering ordinary metacharacters, the OR operator, escape sequences, anchors, quantifiers, grouping, and shorthand character classes, each illustrated with clear code examples and explanations.
Today we introduce common regular expression symbols used in Python, focusing on seven ordinary metacharacters, the OR operator, escape characters, anchors (^ and $), quantifiers (.*, ?, *), and grouping parentheses.
For the ordinary metacharacters, examples show how
import re
str1 = "acb azb abb a6b aab"
result1 = re.findall("a[a-z]b", str1)
result2 = re.findall("a[0-9]b", str1)
result3 = re.findall("a[za6]b", str1)
print(result1)
print(result2)
print(result3)matches substrings where the middle character varies according to the character class.
The OR operator example demonstrates matching either "孙悟空" or "齐天大圣":
import re
str2 = "我是孙悟空,您可以称呼我为齐天大圣!"
result1 = re.findall("孙悟空|齐天大圣", str2)
print(result1).
Escape character examples compare "\n123456", "\n123456" (literal newline) and raw strings r"\n123456", showing how the number of backslashes affects the match of the literal "n".
Anchor symbols ^ and $ are illustrated with re.findall("^你", str6) and re.findall("省$", str6), matching the start or end of a string.
Quantifier examples use patterns like a.b, a*b, a?b, a.*b, and a.*?b on the string "abcdaabb" to show greedy vs. non‑greedy matching.
Grouping with parentheses is shown by extracting digits and Chinese characters: re.findall("a(\d+)b([\u4e00-\u9fa5]+)c", "a321b木头人c") returns the captured groups.
Additional sections cover shorthand character classes such as \d / \D, \s / \S, and \w / \W, each with example strings and explanations of what they match.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
