Regex 101
A primer on writing regexes
Introduction
Matching the beginning of a line using the caret ^
^
The caret or ^
matches the beginning of the line. Anything coming after the caret will only match if it's present at the beginning of any line in a multiline string.
The dot operator .
.
A dot .
matches any single character other than an newline \n
. A dot can be used a wildcard for any single character except for a newline character. This makes it very versatile for matching any character in a specific position within a string.
The end operator $
$
The end operator $
is used to denote the end of a string or the end of line. This is useful for ensuring that a match occurs only at the end of a string or line. The $
operator in regex is not a character but a positional assertion that denotes the end of a line or string.
The asterisk or star operator *
*
The asterisk *
is a quantifier that matches the preceding element zero or more times. This means that the element it follows can appear any number of times, including not at all.
The digit matcher \d
and the non digit matcher \D
\d
and the non digit matcher \D
The \d
used to match any digits (0-9). The \D
operator is used to match any non-digit characters.
The \D
will match any whitespace operator too since they are non digits.
The whitespace matcher \s
and the non whitespace matcher \S
\s
and the non whitespace matcher \S
The \s
matches nay of the white space characters (\r
, \n
, \t
, \f
). The \S
matches any non whitespace character.
The word \w
and the non word \W
\w
and the non word \W
The \w matches a word character, it could be a letter, a digit or an underscore. The \W matches a non-word character, anything that other than what \w matches.
The {}
quantifier
{}
quantifierThe {} quantifier is used to specify the exact number of occurrences, or a range of occurrences, of the preceding element. The syntax within the braces allows for various forms of repetition.
When paired with ,
within the {}
, ranges or "atleast" logic can be used.
Last updated