EMZETT.
Login

RegEx (Regular Expressions)

In short: A compact pattern language for searching, checking, or replacing text based on specific structures — e.g. to test whether an input looks like a valid email address.

In more detail: A regular expression describes a search pattern made of literal characters and special characters with a particular meaning (e.g. \d for a digit, * for “repeated any number of times”). RegEx is extremely powerful, but quickly becomes hard to read for complex patterns — for simple checks (e.g. “does string X contain…”), a normal string method is often clearer and more maintainable.

In Depth

The most important building blocks of a regular expression:

.       - any character
\d      - a digit (0-9)
\w      - a "word character" (letter, digit, underscore)
\s      - a whitespace character (space, tab, line break)
*       - the previous element 0 or more times
+       - the previous element 1 or more times
?       - the previous element 0 or 1 times (optional)
[abc]   - one of the characters a, b, or c
^       - start of the string
$       - end of the string

A simple example — a pattern that roughly checks whether an input looks like an email address:

Pattern: ^[\w.]+@[\w]+\.[a-z]+$
 
"test@example.com"   -> matches
"not-an-email"          -> doesn't match (no @)

RegEx is typically used for three tasks: validation (does an input match an expected format?), search (where in the text does a pattern occur?), and replacement (replace all matches of a pattern with something else, e.g. replace all multiple spaces with a single one).

A well-known, often-cited downside of complex regular expressions is their readability — a densely packed pattern with many special characters is often barely decipherable for someone else (or your own future self in six months) without breaking it down character by character. Another, more technical pitfall is “catastrophic backtracking”: certain poorly constructed patterns can take exponentially long to evaluate for certain inputs, effectively freezing the program (ReDoS, “Regular Expression Denial of Service”) — a reason to construct or test regex patterns with care, especially for user-controlled input.

See also: Strings, Special Characters