I often see regular expressions, but I only talk about methods, but I seldom talk about the following basic concepts:
1. Greedy: + ,*,?, {M, n} and so on are greedy by default, that is, as many matches as possible, also called the maximum match
If ?, It is converted to non-Greedy match and requires support from a later version.
2. obtain: by default, (x | y) is used to obtain the matching data. In many cases, it is only a test and does not necessarily require the matching data, especially in nested matching or big data, non-obtain matching is required (? : X | y), which improves the efficiency and optimizes the program.
3. Consumption: Consumption matching is used by default, and non-consumption matching is usually used in pre-query.
For example, the value of-2-8 must be changed to-02-08.
If/-(\ d)-/is used for the second match, it will start from 8, so that only the first 2 will be replaced.
If/-(\ d )(? =-)/The second match starts from the second-, that is, no characters are consumed-
4. Pre-check: js supports forward and negative pre-check.
As shown above (? = Pattern) is a forward pre-query that matches the search string at the beginning of any string that matches pattern. And (?! Pattern) is a negative pre-query that matches the search string at the beginning of any string that does not match pattern. Negative pre-query is sometimes used to expand [^]. [^] is only a few characters, and ?! The entire string.
5. Callback: It is generally used for replacement, that is, return unused replacement values based on the unnecessary Matching content, which simplifies the program and requires support from a later version.
6. Reference: \ num indicates the reference that matches the obtained num.
For example, '(.) \ 1 \ 1' matches AAA type. '(.) (.) \ 2 \ 1' matches the ABBA type.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Of course there are many other things that need to be mastered.
You can solve the regular expression problem in either of the following ways:
1. Category, that is, to list various situations based on all possibilities, such as the number within 2003
0 0
1-999 [1-9] \ d}
1000-1999 1 \ d {3}
2000-2003 200 [0-3]
So the final match is (0 | [1-9] \ d {200} | 1 \ d {3} | [0-3])
2. Grouping: divides the entire sentence into different minimum units, such as ', %, and _.
Can be grouped, that is, allowed to exist,
''
% An even number greater than 2 can be subdivided into multiple smaller 2 character units
__
[^ '% _] Not above
So the final match is ^ (''| % |__ | [^ '% _]) * $
--------------------------------------------------------------------------------
Support for replace + function 5.5 +
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]