The Dot or Period in Regular Expressions

Published by Brandon on

Ever wonder what the dot or period in regular expressions is? It’s quite simple what it means, actually. It matches with any character, except the newline. So if my regular expression was the string “This is my regular expression string”, and my pattern was .*, then it would match all the characters in the string except newline.

Let’s check out an example in python with the regular expression module.

import re

test = "This is a test string"

x = re.search('.*', test)

print(repr(x))

Output:

<re.Match object; span=(0, 21), match='This is a test string'>

Notice that the regular expression matched the whole string.

The Literal Period in a Regular Expression

Maybe you want to match with the literal period instead of the special meaning of the period. In that case, you just need to put a backslash (\) before the period.

import re

test = "This is period .! "

x = re.search('\.!', test)

print(repr(x))

Here the output is:

<re.Match object; span=(15, 17), match='.!'>
Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *