Regular expressions pcre2 cheatsheet

Regular expressions pcre2: Using regex in tools

7 common Regular expressions pcre2 tasks.

Search with grep

Print lines made only of digits. -E enables extended regular expressions.

grep -E '^[0-9]+$' file.txt

Use lookarounds with grep

Print only the matching part, using Perl-compatible syntax with -P (GNU grep).

grep -oP '\d+(?=px)' styles.css

Rewrite text with sed

Swap two numbers around a hyphen, using capture groups in the replacement.

sed -E 's/([0-9]+)-([0-9]+)/\2-\1/' file.txt

Match in JavaScript

Extract the parts of a date with a regular expression literal.

const [, year, month, day] = "2026-10-30".match(/(\d{4})-(\d{2})-(\d{2})/);

Replace in JavaScript

Replace every run of whitespace with a single space. The g flag replaces all matches.

text.replace(/\s+/g, " ")

Find all matches in Python

Return every run of digits in a string. Use raw strings so backslashes aren't treated as escapes.

import re

re.findall(r"\d+", text)

Replace in Python

Replace matches using a pattern and a replacement, with \1 style references.

re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", text)

Was this page helpful?