bhylu.com

Advertisements

RegEx

A regular expression describes a text pattern. Use it for a defined matching task, not as a substitute for understanding a structured format.

Understand the idea

re.fullmatch requires the entire string to match, while search finds a matching part. Raw string literals make backslashes in patterns easier to read. Keep patterns bounded and test invalid inputs as well as valid ones. A simple pattern should not be advertised as complete validation for a complex format such as every possible email address.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

import re
pattern = r"BK-[0-9]{4}"
for code in ["BK-2048", "xBK-2048", "BK-12"]:
    print(bool(re.fullmatch(pattern, code)))

Read the result

The results are True, False, and False because only the first string has the exact required shape.

Try one change

Add lower-case input to your tests and decide whether the code format is intentionally case-sensitive.