Metacharacters in Python

Metacharacters regular expressions more powerful than normal string methods.

Note:
We use a raw string in the following examples, which is a normal string with an “r” in front of it. We do this to avoid escaping any character that is part of the string.

The . (dot) metacharacter – it matches any character other than a new line.

Example:

import re

pattern = r"D.n"

if re.match(pattern, "Dan"):
	print("Match 1")
	
if re.match(pattern, "Amy"):
	print("Match 2")

if re.match(pattern, "Don"):
	print("Match 3")

if re.match(pattern, "Danny"):
	print("Match 4")

if re.match(pattern, "dan"):
	print("Match 5")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python3 file.py
Match 1
Match 3
Match 4
ddn_ro@linux:~/Desktop$

The ^ and $ metacharacters – They match the start and end of a string, respectively.

Example:

import re

pattern = r"^D.n$"

if re.match(pattern, "Dan"):
	print("Match 1")
	
if re.match(pattern, "Amy"):
	print("Match 2")

if re.match(pattern, "Don"):
	print("Match 3")

if re.match(pattern, "Danny"):
	print("Match 4")

if re.match(pattern, "dan"):
	print("Match 5")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Match 1
Match 3
ddn_ro@linux:~/Desktop$

The pattern “^D.n$” means that the string should start with “D”, then follow with any character, except a newline, and end with “n”.

Leave a Reply