Skip to content
LineOtter

Regular expressions: a practical starter with examples

The regex building blocks you will actually use, how flags change matching, and how to filter lines and replace text safely.

Building blocks

Letters match themselves. A dot matches any character. [0-9] matches one digit and [a-z] one lowercase letter. Add + for “one or more”, * for “zero or more”, ? for “optional” and {4} for “exactly four”.

^ anchors to the start and $ to the end. Parentheses group and capture, so ([0-9]{4})-([0-9]{2}) captures the year and month from 2024-01 as $1 and $2.

Characters with special meaning, such as . + ? ( ) [ ], need a backslash in front when you mean them literally.

Flags

g finds every match instead of only the first. i ignores case. m makes ^ and $ work on each line. s lets the dot match line breaks. u enables full Unicode, such as emoji as single characters.

Using a pattern as a tool

Keep matching lines works like grep: paste a log and keep only the lines containing ERROR. Remove matching lines does the opposite, such as dropping every line ending in @example.com.

Replace previews a find-and-replace. Tick g to replace every match, and use $1 to reuse captured text: pattern ([0-9]{4})-([0-9]{2}) with replacement $2/$1 turns 2024-01 into 01/2024.

Patterns with nested repetition, such as (a+)+, can take extremely long on some text. If the page stops responding, reload it and simplify the pattern.

Patterns you can adapt

Digits only on a line: ^[0-9]+$ with the m flag.

A simple email check: ^[^@ ]+@[^@ ]+[.][a-z]{2,}$ with the i flag. It rejects obvious mistakes; real validation should send a confirmation email.

Lines containing a word, case-insensitive: type the word and tick i, then choose Keep matching lines.

Dates written as YYYY-MM-DD: ([0-9]{4})-([0-9]{2})-([0-9]{2}), with the three parts available as $1, $2 and $3 in Replace.

Testing a pattern before you rely on it

Paste examples that should match and examples that should not, then check the match count for both. Most regex bugs are patterns that match too much: a dot where you meant a literal dot, or a missing ^ and $ so the pattern matches part of a longer line.

Keep a few awkward test lines, such as empty lines, very long lines and lines with accents or emoji, and paste them in whenever you change the pattern.

Tools for this