Objective

Understand “regex” in under fives minutes.

Definition

Regex (regular expressions), are expressions used to match specific patterns in strings.

Why do we use regex?

Here’s an example: How can we validate whether our user inputs a valid birth date year (we’re not checking whether the year is before today’s current year).

Non-regex way:

if string is not of length four: return False for each character in the string if character is not a digit: return False return True

regex way

if string matches regex ^\\d{4}$ then return True, else False

Below you’ll find a visual aid to understand this regex.

\\d here means digit.

{4} specifies that we’re looking for four of whatever precedes it, which is a digit.

image.png

(website used: https://www.regexplained.co.uk/)

^ specifies the start of a string.

$ specifies the end of as string.

Using ^ and $ are important as shown below. We get a match for the string on the fourth line because we aren’t specifying that the string should start with four digits.