javascript regular expression summary

  • 2021-01-11 01:54:15
  • OfStack

tool

Regexpal is an online Javascript regular expression processor, the address is: http: / / www regexpal. com

Learning regular is important to practice operation, might as well for example:

Matching number: 707-827-7019

Character set matching

[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]
\d matches arbitrary Arabic numerals
\D matches any non-Arabic numerals

. Matches any character

\d\d\d\D\d\d\d\D\d\d\d\d\D
\d\d\d.\d\d\d.\d\d\d\d.

Capture grouping and backward application

Use parentheses () to create a group and \1 to backreference the contents of the captured group

(\d)\d\1 matches 707

Complete matching number:

^(\(\d{3}\)|^\d{3}[.-]?)?\d{3}[.-]?\d{4}$
^ represents the starting position of line 1
Represents the starting character of the capture group
\(Indicates the open parenthesis
\d{3} means to match 3 digits
\) denotes the closing parenthesis
| said choice
[-] & # 63; Matches 1 optional dot or hyphen
Capture the end character of the group
The & # 63; Indicates that grouping is optional
$indicates the end of the line

The border

Matches the starting position of a line or string using the decarcharacter ^
Use the dollar sign $to match the position at the end of the line or string

quantifiers

The quantifier is greedy by default
Greedy quantifiers match the entire string first. When he tries to match, he selects as many things as he can, the entire input. The quantifier matches the entire character first, and if it fails, it goes back 1 character and tries again. This process is called backtracking.
The lazy quantifier looks for matches from the starting position of the target. Examine the string one character at a time, looking for a match. Finally, he tries to match the entire string.
The possessive quantifier covers the entire target and then tries to find a match, but it only tries once and doesn't backtrack.
If used.* matches any character zero or more times

Greedy quantifiers

Using curly braces {} limits the number of times a pattern matches within a certain range. In addition, an unmodified quantifier is a greedy quantifier
7 {1} and + 7
7 {0} and 7 *
7 the & # 63; With 7 {0, 1}
It's essentially 1
7{m,n} matches m to n times

Lazy quantifiers

Add ? to the end; It makes the quantifier lazy
7 the & # 63; The & # 63; The first 7 & # 63; Match zero or 1 7, nothing matches after laziness
7 * & # 63; Match zero 7's
7 + & # 63; Match 1 7
7{m,n}? Matches m with 7

For regular matching html, the xml tag will be written next time


Related articles: