Member-only story

Python: Getting Started with Regex (with examples)

Tomas Svojanovsky
4 min readSep 7, 2023

--

Regex is a powerful tool for extracting values from a string or validating strings.

While they may seem hard to learn initially, they are not that difficult to start with. They have a lot of rules for matching string patterns. They are straightforward, with a few examples you will have an idea of how they work. With some practice, you will be able to create your own patterns.

Gettings started

  1. The dot regex matches any character (including whitespace characters). You can use it to indicate that you don’t care which character matches.
  2. You want to match text that begins and ends with the character
    y and an arbitrary number of characters in between.
  3. ? is zero or one character. There is another use of the question mark. It is nongreedy pattern matching. We will see it in action in the next example
import re

text = """A blockchain, originally block chain,
is a growing list of records, called blocks,
which are linked using cryptography.
"""

print(re.findall("b...k", text)) # ['block', 'block', 'block']
print(re.findall("y.*y", text)) # ['yptography']
print(re.findall("blocks?", text)) # ['block', 'block', 'blocks']
  • The first argument of findall from re module is the regex itself

--

--

Tomas Svojanovsky
Tomas Svojanovsky

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet