Regular expressions pcre2 cheatsheet

Regular expressions pcre2: Quantifiers, groups and alternation

8 common Regular expressions pcre2 tasks.

Repeat a pattern

Match between two and four letters a. Also: * zero or more, + one or more, ? optional.

a{2,4}

Match as little as possible

Add ? after a quantifier to make it lazy. This matches the shortest text between the quotes.

".*?"

Match one of several options

Match either cat or dog, whichever appears.

cat|dog

Capture parts of a match

Capture the year, month and day of an ISO date as groups 1, 2 and 3.

(\d{4})-(\d{2})-(\d{2})

Group without capturing

Group for alternation or repetition without creating a numbered group.

(?:https?|ftp)://

Name a capture group

Capture a year by name. JavaScript, PCRE and Java use (?<name>...); Python uses (?P<name>...).

(?<year>\d{4})

Match repeated text

Match a repeated word such as the the, using a backreference to the first group.

\b(\w+)\s+\1\b

Ignore case

Match hello in any case. Many tools use an i flag instead.

(?i)hello

Was this page helpful?