Regex: Metacharacters

Specify the position

Metacharacter Explanation
^ Beginning of line
$ End of line
\A Beginning of string
\z End of string
\Z End of string (excluding line endings)
\b Word boundaries
\B Non-word boundaries

Special characters

Metacharacter Explanation
\ Escape
\t Tab
\n Newline (CR)
\r Newline (LF)
\f New page
\d Digits
\D Non-digits
\s Whitespace (space, tab, neewline and new page)
\S Non-whitespace
\w Word (alphanumeric characters plus ”_“)
\W Non-word

Any character and repetition (quantifiers)

Default*1 Lazy*2 Greedy*3 Explanation
. Any single character (excluding line feed code)
* *? *+ The previous character / group is 0 or more times
+ +? ++ The previous character / group is 1 or more times
? ?? ?+ The previous character / group is 0 or 1 times
{n} {n}? {n}+ The previous character / group is n times
{n,} {n,}? {n,}+ The previous character / group is n or more times
{n,m} {n,m}? {n,m}+ The previous character / group is n times or more, m times or less

*1: Match the longest part that meets the conditions. Priority is given to matching the entire pattern.
*2: Match the shortest part that meets the conditions.
*3: Match the longest part that meets the conditions. Priority is not given to matching the entire pattern.

e.g. abcXdefX
Default: ^.*X -> Matches “abcXabcX”.
Lazy: ^.*?X -> Matches “abcX”.
Greedy: ^.*+X-> Not match. ^.*+ -> Matches “abcXabcX”.

Matches any of the specified characters

Metacharacter Explanation
() Grouping
| Or (strings)
[] Or (one character)

e.g. |

Regex Explanation
abc|mno|xyz Simple (One of abc, mno, xyz)
abc.*X|m+o|xy?z Include metacharacters in candidates (abcXXX, mXo, xz, etc.)
(abc|mno|xyz)X Combine with other strings (One of abcX, mnoX, xyzX)
(abc|mno|xyz)* Combine with quantifiers (abcabc, mnoabcxyz, etc.)

e.g. []

Regex Explanation
[abc] Simple (one of a, b, c)
[^abc] Negation (one of other than a, b, c)
[a-z] Range (lowercase)
[A-Z] Range (uppercase)
[0-9] Range (digits)
[a-zA-Z] Or (a to z or A to Z)
[a-z&&[d-f]] And (a to z and d to f)
[a-z&&[^d-f]] Subtraction (a to z excluding d to f)

Lookahead and lookbehind

Metacharacter Explanation e.g. Explanation
?= Positive lookahead foo(?=bar) Matches a “foo” that is followed by a “bar”.
?! Negative lookahead foo(?!bar) Matches a “foo” that is not followed by a “bar”.
?<= Positive lookbehind (?<=bar)foo Matches a “foo” that is preceded by a “bar”.
?<! Negative lookbehind (?<!bar)foo Matches a “foo” that is not preceded by a “bar”.
Hirota Yano / Programmer
Born in 1988, based in Japan.
© yanohirota.com