Basic Metacharacters
Lesson 6 of 28 in Coddy's RegEx in Python course.
Metacharacters are special characters in regex that have unique meanings and functions. They help define the patterns for matching text in a powerful and flexible way.
Here are some of the most common metacharacters and their meanings:
<strong>.</strong>(Dot): Matches any single character except a newline.<strong>^</strong>(Caret): Matches the start of a string.<strong>$lt;/strong>(Dollar Sign): Matches the end of a string.<strong>*</strong>(Asterisk): Matches zero or more repetitions of the preceding element.<strong>+</strong>(Plus Sign): Matches one or more repetitions of the preceding element.<strong>?</strong>(Question Mark): Matches zero or one repetition of the preceding element.<strong>[]</strong>(Square Brackets): Used to define a character class.<strong>|</strong>(Pipe): Acts as an OR operator.<strong>()</strong>(Parentheses): Groups patterns together.
Here is a simple example using the dot . metacharacter:
import re
text = "cat, cot, cut, c.t"
pattern = "c.t"
matches = re.findall(pattern, text)
print(matches) # Output: ['cat', 'cot', 'cut', 'c.t']In the above example, the pattern c.t matches any three-character string that starts with "c" and ends with "t", with any single character in between.
Challenge
EasyWrite a program that uses the . metacharacter to find all three-letter words in the string "bat, bet, bit, but, bot".
Try it yourself
import re
text = "bat, bet, bit, but, bot"
pattern = "???" # Complete here
matches = re.findall(pattern, text)
print(matches)All lessons in RegEx in Python
1Introduction
Introduction3Basic Pattern Syntax
Basic MetacharactersLiteralsCharacter ClassesRangesCommon Predefined ClassesAdvanced Predefined Classes