Menu
Coddy logo textTech

Escape Metacharacters

Lesson 22 of 28 in Coddy's RegEx in Python course.

In regex, certain characters have special meanings. To match these characters literally, you need to "escape" them by prefixing them with a backslash \. Here are some common metacharacters that need to be escaped:

  • .: Matches any character except newline.
  • *: Matches 0 or more repetitions of the preceding element.
  • +: Matches 1 or more repetitions of the preceding element.
  • ?: Matches 0 or 1 repetition of the preceding element.
  • ^: Matches the start of a string.
  • $: Matches the end of a string.
  • |: Acts as an OR operator.
  • (): Groups patterns.
  • []: Creates a character class.
  • {}: Specifies repetitions.
import re

text = "The price is $5.99"
pattern = r"\$5\.99"
matches = re.findall(pattern, text)

print(matches)  # Output: ['$5.99']

In the above example, the pattern \$5\.99 matches the literal string "$5.99". The $ and . characters are escaped to match them literally.

Try it yourself

This lesson doesn't include a code challenge.

All lessons in RegEx in Python