1. Regular expressions are expressions that detect and match strings. 2. Regular expressions are description rules and are well supported by mainstream languages. 3. String verification, search and replacement are the main usage scenarios of regular expressions.
Character range matching:
regular expression
illustrate
correct
mistake
A
Exactly match a single character
A
a
x/y
2 characters allowed
y
n
[xyz]
Character set, allowing any single character in the set to appear
z
c
[a-z] [A-Z] [0-9]
character range
a D 8
A a A
[^xyz] [^0-9]
Characters are not allowed to appear in the set
0 A
y 8
Metacharacters:
Metacharacters refer to characters that refer to a certain type of characters through some special expressions, which are called metacharacters.
regular expression
illustrate
correct
mistake
\d
Match any single number
8
i
\D
Matches any single character outside the \d rule
i
8
\w
Matches any single alphanumeric underscore
Y
&
\W
Matches any single character except \w
&
Y
\s
Match a single space
x
\n
Matches a single newline character
x
.
Matches any single character (except newline)
-
\r\n
\.
Special characters, only matches .
.
1
Repeat the match multiple times:
regular expression
illustrate
correct
mistake
A{3}
Exact N times matching
AAA
AA
A{3,}
Appear at least N times
AAA
AA
\d{3,5}
Agree on the minimum and maximum number of occurrences
1234
12
\d*
Can appear zero to infinite times, equivalent to {0,}