Regular expressions are also called regular expressions. (English: Regular Expression, often shortened to regex, regexp, or RE in code)
Rules for processing strings
- You can only handle strings
- It is a rule: you can verify that a string conforms to a rule (test), and you can capture the content of the string that does (exec/match…).
let str = "Good good study, day day up!;
//=> < span style = "box-sizing: border-box; color: RGB (74, 74, 74);
let reg = /\d+/;
reg.test(str); //=>false
str = "2020-04-07";
reg.exec(str); //=>["2020",index:0,inputs:" raw string "]
Copy the code
1. Fundamentals of RegExp
1, define,
Definition: is a rule for handling strings
- A re in JS is a reference data type
2. How to write regular expressions
Since the constructor is passing a string, \ needs to write two to represent a slash
- Let reg = /\d+/g;
- Let reg = new RegExp(“\\d+”,”g”);
- When some characters in the re need to be variables; I would have chosen this way
The difference between the two approaches
- When part of the regular expression is a value stored in a variable
//1. Both slashes are metacaracters (if the regular contains the value of a variable, they cannot be created as literals).
let type = "xiaozhima";
reg = /^@"+type+"@$/;
console.log(reg.test("@xiaozhima@")); //=>false
console.log(reg.test('@"""typeeeee"@')); //=>true
//2. In this case, only the constructor method can be used (since the rule is a string, only then can string concatenation be performed).
reg = new RegExp("^ @"+type+"@ $");
console.log(reg.test("@xiaozhima@"));//=>true
Copy the code
3, regular use
Re the method on RegExp. Prototype
- Match the test
- Capture the exec
- Match the test
- Write a re (a set of rules) that tests whether a string conforms to the rules;
- Capture the exec
- Write a re (a set of rules) to retrieve the characters in a string that conform to the rules
The String string. prototype supports regular expression processing methods
- replace
- match
- splite
- .
4, regular composition (list only a few commonly used)
A regular expression consists of modifiers and metacharacters.
- Metacharacters consist of ordinary characters and some special characters:
- Common characters include uppercase and lowercase letters and numbers,
- Special metacharacters have special meanings, which we will explain below.
1). The modifier
Used outside the regular:
- Such as:
/abc/i
In thei
character | meaning | English full name |
---|---|---|
i | Ignore case | ignoreCase |
m | Multi-line matching | multiline |
g | The global matching | global |
s | Make the dot match any character, including \n and \r | |
. | . |
– $2) characters
What’s in between the slashes we call metacharacters
- Such as:
/abc/i
In theabc
Common metacharacter
Just plain letters and numbers in upper and lower case;
Special metacharacters
Metacharacters with special meanings
character | meaning |
---|---|
\ | Escape characters (to convert a character with a special meaning to itself, or to escape a normal character with a special meaning) |
\d | A number ranging from 0 to 9 |
\D | Any character except 0 to 9 |
\w | Digits, letters, and underscores (lowercase W) |
\W | Any character except numbers, letters, and underscores (capital W) |
^ | What character begins with |
$ | What character does it end with |
. | Represents all characters except newlines |
\n | On behalf of the line |
\s | A whitespace character (containing Spaces, tabs, newlines, etc.) |
\t | A TAB character (one TAB key: 4 Spaces) |
\b | Matches the boundary of a word |
—- | —- |
x|y | Representative or; X or y |
[xyz] | Representative or; X or Y or Z (the difference is that [] can only be written before and after a single character, while | can be written before and after a group of numbers) |
[^xy] | Any character other than xy |
[a-z] | Any character from A to Z Lowercase letters |
[^a-z] | Any character except a and z |
(a) | Grouping and prioritizing |
(? 🙂 | Only match, not capture |
(? =) | Positive positive forecheck |
(? !). | Positive negative forecheck |
. | . |
Quantifier metacharacters
Are used after other metacharacters
- For example: / ABC {3}/ => {3}
character | meaning |
---|---|
? | The preceding character should occur 0 or 1 times |
+ | Only one or more occurrences of the preceding character are required |
* | The preceding character should appear 0 or more times |
{n} | The preceding character should appear n times in a row |
{n,m} | The preceding character should appear n to m times in a row |
{n,} | The preceding character should appear n to more times in a row |
. | . |
Mind mapping: Fundamentals of Regularity
2. Regular match (test)
Write a re (a set of rules) that tests whether a string conforms to the rules;
1, grammar,
- Regex.test(string)
2, return value
- Conforms to regular rules: returns TRUE
- Invalid regular rule: returns FALSE
3, some examples 🌰 exercises
\d,? ,{n,m}
var str = 'Small Sesame 666';
var reg = /\d/; // As long as the string contains a number
console.log(reg.test(str)) // true
console.log(reg.test('werwf2ergdfg'))//true
console.log(reg.test('aefasdfsdfsf'))//false
console.log(reg.test('3453245254')) // true
var reg = /\d? /; // The number appears 0 or 1 times
console.log(reg.test('xiaozhima666')) // true
console.log(reg.test('werwf2ergdfg'))//true
console.log(reg.test('aefasdfsdfsf'))//true
console.log(reg.test('3453245254')) // true
var reg = / / \ d {2, 4}; // Does the string contain two or three consecutive digits or four consecutive digits
// /\d\d/ /\d\d\d/ /\d\d\d\d/
console.log(reg.test('xiaozhima666')) // true
console.log(reg.test('werwf2ergdfg'))//false
console.log(reg.test('aefasdfsdfsf'))// false
console.log(reg.test('3453245254')) // true
var reg = /\d{2}/; // The string contains two consecutive numbers
console.log(reg.test('xiaozhima666')) // true
console.log(reg.test('werwf2e3rgdfg'))// false
console.log(reg.test('aefasdfsdfsf'))// false
console.log(reg.test('3453245254')) // true
Copy the code
Exercises related to the beginning ^ and ending $
- A ^ $: string must all satisfy the re
- No ^ $in the re: as long as there are characters in the string that match the re
var reg = /^\d/; // Requires the string to start with a number
console.log(reg.test('xiaozhima666')) // false
console.log(reg.test('werwf2e3rgdfg'))// false
console.log(reg.test('aefasdfsdfsf'))// false
console.log(reg.test('3453245254')) // true
var reg = / / ^ \ d {2, 3}; // Require the string to start with two or three digits
console.log(reg.test('1xiaozhima666')) // false
console.log(reg.test('22werwf2e3rgdfg'))// true
console.log(reg.test('432aefasdfsdfsf'))// true
console.log(reg.test('3453245254')) // true
var reg = / / d {2, 3}; // The string must have two or three consecutive d's
console.log(reg.test('1xiaozhima666')) // false
console.log(reg.test('22werwf2e3rgdfg'))// false
console.log(reg.test('432aefasdfsdfsf'))// false
console.log(reg.test('3453245254')) // false
var reg = /\d$/; // The string needs to be a numerically terminated character
console.log(reg.test('1xiaozhima666')) // true
console.log(reg.test('22werwf2e3rgdfg'))// false
console.log(reg.test('432aefasdfsdfsf'))// false
console.log(reg.test('3453245254')) // true
var reg = / \ d {4, 6} $/; // A string ending in 4-6 digits
console.log(reg.test('1xiaozhima666')) // false
console.log(reg.test('22werwf2e3rgdfg'))// false
console.log(reg.test('432aefasdfsdfsf3456'))// true
console.log(reg.test('3453245254')) // true
// The regular string has ^ $, which means that all strings must be regular
// There is no ^ $in the re as long as there are characters in the string that match the re
// var reg2 = /\d/;
var reg = /^\d$/; // Start with a number and end with a number: start with a number and end with a number
console.log(reg.test('432aefasdfsdfsf3456'))// false
console.log(reg.test('3453245254')) // false
console.log(reg.test('3333')) // false
console.log(reg.test('1')) // true
console.log(reg.test('9'))// true
console.log(reg.test('4'))// true
console.log(reg.test('5'))// true
console.log(reg.test('8'))// true
var reg = / ^ \ d {2, 3} $/;// Start with two or three numbers and end with the same two or three numbers
// That is, this re can only match two or three digit strings
console.log(reg.test('432aefasdfsdfsf3456'))// false
console.log(reg.test('3453245254')) // false
console.log(reg.test('3333')) // false
console.log(reg.test('1')) // false
console.log(reg.test('9'))// false
console.log(reg.test('4'))// false
console.log(reg.test('5'))// false
console.log(reg.test('8'))// false
console.log(reg.test('18'))// true
var reg = /^\d+.\d{2}$/;
console.log(reg.test('123.345'))// false
console.log(reg.test('123r34')) // true
console.log(reg.test('1235345'))//true
console.log(reg.test('123r345')) // false
console.log(reg.test('123 345')) // false
console.log(reg.test('123r45')) // true
var reg = /\\d+/;// To match a \ followed by 1 to multiple d characters' \dd...... '
console.log(reg.test('qqwewer'))// false
console.log(reg.test('134543'))// false
console.log(reg.test('134543d'))// false
console.log(reg.test('dd'))// false
console.log(reg.test('\dd'))// true
console.log(reg.test('\\dd')) //true
Copy the code
Brackets []: or
- The characters in brackets usually represent themselves
- In [the] : quantifiers metacharacters |. No longer has a special meaning.
- \d in brackets is still 0-9
- The character ‘-‘ in [] corresponds to the corresponding Aske code value;
- [] : Advice is best placed at the end
- For example: / [\ w @ #?] + /
- There are no multiple digits in brackets
var reg = /[a-c]/;// select * from ABC; // select * from ABC
console.log(reg.test('aeadfgergdfgd'))//true
console.log(reg.test('234werrfrb')) // true
console.log(reg.test('acaca')) // true
console.log(reg.test('bbbbb')) // true
// the character '-' in [] corresponds to the corresponding Aske code value
Var reg = /[c-a]/; Is not allowed, will be an error
// var reg = /[C-a]/ ;// ASCII:67(大C)-97(小a)
var reg = /[c\-a]/ ;// c or '-' or a; The '-' here doesn't make sense, it's just a '-'
var reg = / [.] /;// The dot in [] stands for the dot itself
/ / = > [] : in the quantifier metacharacters |. No longer has a special meaning.
var reg = $/ / ^ [1.2];// This re can only match one character; One or. Or two
console.log(reg.test('1.2'))//false;
console.log(reg.test('1q2'))//false
console.log(reg.test('1')) // true
console.log(reg.test('2'))// true
Copy the code
Point of practice
var reg = 1.2 $/ / ^;// The re has an arbitrary character between the beginning and end of 1 and 2
console.log(reg.test('1.2'))/ /; true
console.log(reg.test('1q2'))//true
console.log(reg.test('1')) // false
console.log(reg.test('2'))// false
Copy the code
Escape exercises
- Escape in a re: The escape of a character with a special meaning in a re from the character itself
- Escape in string: the escape of a character with a special meaning into the character itself;
var reg = $/ / ^ 1 \. 2;// There is a dot between the beginning and the end of the re
console.log(reg.test('1.2'))/ /; true
console.log(reg.test('1q2'))//false
console.log(reg.test('1')) // false
console.log(reg.test('2'))// false */
// Escape a string from a regular string
// To escape a regular is to escape a character with a special meaning in the regular
// To escape a string is to escape a character with a special meaning in the string into the character itself; '" \
Copy the code
Vertical | : or related exercises
- Direct x | y will mess priority problems, normally we write is accompanied by parentheses to group, because parentheses change processing priority = > parentheses: grouping
var reg = 18 | / 19 /;// Contain 18 or 19
console.log(reg.test('18'))
console.log(reg.test('the'))
console.log(reg.test('189'))
console.log(reg.test('1819'))
console.log(reg.test('819'))
console.log(reg.test('1918'))
console.log(reg.test('118'))
var reg = 19 / / ^ 18 |;// False is true;
console.log(reg.test('18')) // true
console.log(reg.test('the')) // true
console.log(reg.test('189'))//true
console.log(reg.test('1819'))//true
console.log(reg.test('819'))//true
console.log(reg.test('1918'))//true
console.log(reg.test('118')) // false
console.log(reg.test('119')) // true
var reg = 18 | $19 / / ^;// True; // True;
console.log(reg.test('18')) // true
console.log(reg.test('the')) // true
console.log(reg.test('189'))//true
console.log(reg.test('1819'))//true
console.log(reg.test('819'))//true
console.log(reg.test('1918'))//false
console.log(reg.test('118')) // false
console.log(reg.test('119')) // true
// Write a re that is true only if 18 or 19 matches; Everything else is false;
var reg = $/ / ^ 18 | (19);// Can only match 18 or 19
console.log(reg.test('18')) // true
console.log(reg.test('the')) // true
console.log(reg.test('189'))//false
console.log(reg.test('1819'))//false
console.log(reg.test('819'))//false
console.log(reg.test('1918'))//false
console.log(reg.test('118')) // false
console.log(reg.test('119')) // false
var reg = $/ / ^ [19] 18 |;/ / only match 1 8 | 1 one of the nine to five
var reg = / ^ 1 $/ [89]; // Start with 1 and end with 8 or 9;
var reg = $/ / ^ 9 [18]; // Start with 1 or 8 and end with 9
var reg = / ^ 1 $/ (8 | 9);// Start with 1 and end with 8 or 9;
Copy the code
4, application practice
-1), write a re to match whether the user enters a valid phone number (broad)
Rules:
- 1. Start with 1
- 2. Eleven digits
- 3, the second can not 012
let rex = /^1[3-9]\d{9}$/
Copy the code
-2), write a re that matches significant digits
Rules:
- 1, may or may not appear: [+-]?
- 2, a 0-9 can be more than the first not is 0 (\ | d (1-9] [\ d +))
- (.\d+)? (.\d+)?
let reg = / ^ (+ -)? (\d|([1-9]\d+))(\.\d+)? $/;
Copy the code
-3), write a re to verify the real name
Rules:
- /^[\u4E00-\u9FA5]$/
- 2. The name contains 2 to 10 characters
- (·[\u4E00-\u9FA5]{2,10}){0,2}
let reg = / ^ [\ u4E00 - \ u9FA5] {2, 10} (· [\ u4E00 - \ u9FA5] {2, 10})} {0, 2 $/;
Copy the code
-4), write a re to match ages between 18 and 65
Rules:
- 1, the integer
- 18 and 19; 20-59 : [2-5]\d ; 6 [0-5)
let reg = /^(1[89]|[2-5]\d|6[0-5])$/;
Copy the code
-5), write a re to match mailbox
Rule 1: The email address contains letters, digits, underscores (_), hyphens (-), and underscores (_). Consists of several parts, but -/. Cannot appear consecutively and cannot be used as a beginning
1. Start with an underscore (1 to more than one digit)
2, can also be – alphanumeric underscore or. Alphanumeric underscore, the whole zero to multiple
=> \w+((-\w+)|(.\w+))*
Rule 2:
1, @ followed by: numbers, letters (1-digit)
=> @[A-Za-z0-9]+
2, to @ after the name of the supplement
- Many domain. Com. Cn
- Enterprise email [email protected]
=> ((.|-)[A-Za-z0-9]+)*
(. 3, matching the last domain com/.cn/.org/.edu/.net…).
=> .[A-Za-z0-9]+
let reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
Copy the code
-6), write a re can match the ID number
Rules:
- 1. There are 18 persons in total
- 2. The last digit could be an X
- 3, ID card top six: province, city and county (the first cannot be 0)
- 4, was born in 19 or 20: ((20) 19 | \ d {2})
- In 5, 01-12: (0 [1-9] | 1 [2-0])
- 6, date – 31: (0 01 [1-9] | [1-2] \ | 3 d [01])
- 7, the last = > X or digital (\ d | X)
- (\d {2}(\d)) (\d {2}(\d))
let reg = /^[1-9]\d{5}((19|20)\d{2})(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[01])\d{3}(\d|X)$/i;
Copy the code
-7), write a regular expression that matches the rules of the password entered by the user;
Rules:
- 1, 8-18
- 2. Have both upper and lower case letters and numbers
function judge(str) {
if (str.length < 8 || str.length > 18) return false
if (!/[A-Z]/.test(str)) return false
if (!/[a-z]/.test(str)) return false
if (!/\d/.test(str)) return false
return true;
}
let reg = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]) [A zA - Z0-9] {8} 16 $/
//=> Special characters are required
let reg = / ^ (? =.*\d)(? =.*[a-z])(? =.*[A-Z])(? =. * [-] #? & *) [a - zA - Z0-9 #? & * -] {8} 16 $/
//=> The password consists of 8 to 18 digits or letters
let reg = / ^ [0-9 a Za - z] {8} 16 $/;
Copy the code
Also share a regular lookup tool: novice tool
3. Regular capture (EXEC)
Write a re (a set of rules) to retrieve the characters in a string that conform to the rules
1, grammar,
- Re. Exec (string)
2, the premise,
The prerequisite for regular capture is that the current re matches the string. If it does not match, the result of capture is null
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /^\d+$/;
console.log(reg.test(str)); //=>false
console.log(reg.exec(str)); //=>null
Copy the code
3, return value
- If a matching text is found, an array is returned
- First item in the array: the content captured this time
- Other items: the content captured separately by the corresponding small group
- Index: the starting index of the currently captured content in the string
- Input: raw string
- .
- Not found, otherwise return
null
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/;
console.log(reg.exec(str));
Copy the code
4. Features of capture
-1) Laziness
Each time we execute exec, only one match that conforms to the regular rules can be captured. By default, we execute 100 times, and the obtained result is always the first match, and the rest cannot be captured
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/;
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
console.log(reg.exec(str));
Copy the code
Lazy solution
To address laziness, we need to know why regulars have this feature in the first place.
- So let’s first take a look at what the regex that we wrote has in the console output
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/;
console.dir(reg);
Copy the code
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/;
console.log(reg.lastIndex); //=> select * from '0' where '0' = '0'
console.log(reg.exec(str));
console.log(reg.lastIndex); //=>0 the first time the match is captured, the lastIndex is not changed, so the next exec is still from the beginning of the string, and the first match is always found
Copy the code
Reg. lastIndex: The starting index position for the next match of the current re (then we can see why the re is lazy)
- Reason for lazy capture: by default
lastIndex
The value of is not changed, and each search is at the beginning of the string, so the first one is always found
Now that we know why Re is so lazy, we can do something about it 😄
Solution: global modifier g
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/g;
console.log(reg.exec(str)); / / = > [...] of "2019"
console.log(reg.lastIndex); //=> set the global match modifier g, the first match, lastIndex will change itself
console.log(reg.exec(str)); / / = > [...] of "2020"
console.log(reg.lastIndex); / / = > 26
console.log(reg.exec(str)); / / = > [...] of "2021"
console.log(reg.lastIndex); / / = > 39
console.log(reg.exec(str)); //=>null; //=>null; //=>null
console.log(reg.lastIndex); / / = > 0
console.log(reg.exec(str)); / / = > [...] of "2019"
Copy the code
- Let’s verify that re and string matching do not matter
lastIndex
let str = "xiaozhima2019xiaozhima2020xiaozhima2021";
let reg = /\d+/g;
if (reg.test(str)) {
//=> Verify that only the re and string match we are capturing
console.log(reg.lastIndex); //=>11 After the TEST match is verified, LASTINDEX has been changed to the result after the first match, so the next capture will not start from scratch
console.log(reg.exec(str)); / / = > [...] of "2020"
}
Copy the code
Requirement exercise: Write a method execAll that can be executed once to capture all matching results (the global modifier g must be set for regular)
~ function () {
function execAll(str = "") {
//=> STR: string to be matched
//=>this: instance of RegExp
// the first thing to do is to verify that the current re is set to G. If the current re is not set to G, the loop will not be captured again, otherwise it will lead to an infinite loop
if (!this.global) return this.exec(str);
//=>ARY stores all last captured information RES stores the contents of each capture (array)
let ary = [],
res = this.exec(str);
while (res) {
//=> store the contents of each capture RES[0] in the array
ary.push(res[0]);
//=> The capture will continue as long as the captured content is not NULL
res = this.exec(str);
}
return ary.length === 0 ? null : ary;
}
RegExp.prototype.execAll = execAll; } ();let reg = /\d+/g;
console.log(reg.execAll("Golden 2019@2020 little sesame")); / / = > [" 2019 ", "2020"]
//=> The MATCH method in a string can capture all matches if executed once (if G is set).
console.log("Golden 2019@2020 little sesame".match(reg));/ / = > [" 2019 ", "2020"]
Copy the code
-2) Greed
By default, the regex is captured according to the longest result matched by the current regex
let str = "Golden 2019@2020 little sesame";
//=> Re capture greed: By default, a re is captured with the longest result that matches the current re
let reg = /\d+/g;
console.log(reg.exec(str)); / / = > [" 2019 ",...]
Copy the code
The greedy solution
Set? After the quantifier metacharacter. : Cupidity during uncapture (taking the shortest result of a regular match)
let str = "Golden 2019@2020 little sesame";
reg = /\d+? /g;
console.log(reg.exec(str)); / / = > / "2",...
Copy the code
Mind mapping: Re matching and capture
Four, regular other common knowledge points
1. Question mark? Five functions in regularization:
Five functions of question marks in re:
- To the left of the question mark is a nonquantifier metacharacter: itself represents a quantifier metacharacter that occurs zero to one time
- To the left of the question mark is the quantifier metacaracter: cupidity at uncapture
- (? 🙂 only matches but does not capture
- (? =) Forward lookup (what must be included)
- (? !). Negative precheck (must not have anything)
2. Three functions of grouping ()
-1) The first function of subgroups is to increase the priority
Requirements: Capture the birth date and gender in the ID number
//=> The first item is the result of a large regular match
//=> Remaining items: Each subgroup matches the captured results individually
//=> If the group is set, but the capture does not need to be separate, can be based on? : to deal with
Copy the code
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text"/>
<button>submit</button>
<h5></h5>
</body>
</html>
<script>
/* Click the submit button on the H5 TAB to show this date of birth and gender */
let inp = document.querySelector('input'),
btn = document.querySelector('button'),
h5 = document.querySelector('h5');
btn.onclick = function(){
let val = inp.value;
var reg = /^[1-9]\d{5}((19|20)\d{2})(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[01])\d{2}(\d)(\d|X)$/i;
let ary = reg.exec(val);
console.log(ary);
if(ary){
// The input is a valid regular
let str = 'This person's date of birth is${ary[1]}years${ary[3]}month${ary[4]}Day; Gender is${ary[5] %2 ? 'male' : 'woman'}`;
h5.innerHTML = str;
}else{
alert('Not a legitimate id number')}}</script>
Copy the code
-2) The second function of small group: group capture
Requirements: capture both {number} and the number separately. For example, the first time {0} is found, the number needs to be obtained separately
//=> Capture both {number} and the number separately. For example, if {0} is found for the first time, you need to obtain 0 separately
let str = "{0} year {1} month {2} day";
//=> select * from 'g' where 'g' = 'g' where 'g' = 'g' where 'g' = 'g' where 'g' = 'g'
let reg = /\{(\d+)\}/;
console.log(reg.exec(str));
console.log(str.match(reg));
/ / / "{0}", "0",...
let reg = /\{(\d+)\}/g;
console.log(str.match(reg)); / / = > [" {0} ", "{1}", "{2}"]
// In the case of multiple matches,match can only obtain the content of large regular matches, but cannot obtain the information of small group matches
//=> Write your own method to complete the requirement
let aryBig=[],
arySmall=[],
res=reg.exec(str);
while(res){
let [big,small]=res;
aryBig.push(big);
arySmall.push(small);
res=reg.exec(str);
}
console.log(aryBig,arySmall); //=>["{0}", "{1}", "{2}"] ["0", "1", "2"]
Copy the code
-3), the third function of small groups: group reference
A group reference is a “\ number” that represents the exact same content as the corresponding group
//=> < span style = "box-sizing: border-box; color: RGB (74, 74, 74);
let str = "book"; //=> < span style = "box-sizing: border-box; color: RGB (74, 74, 74);
let reg = /^[a-zA-Z]([a-zA-Z])\1[a-zA-Z]$/; //=> A group reference means that it represents the same content as the corresponding group by "\ number"
console.log(reg.test("book")); //=>true
console.log(reg.test("deep")); //=>true
console.log(reg.test("some")); //=>false
Copy the code
3. Other methods and cases of regular capture
-1), test can also capture (intended to match)
- RegExp.$& : retrieves the contents of the current grand re
- RegExp.$1~RegExp.$9: Obtains information about the first through the ninth group after the current regular match
let str = "{0} year {1} month {2} day";
let reg = /\{(\d+)\}/g;
console.log(reg.test(str)); //=>true
console.log(RegExp. $1); //=>"0" obtains the content matched by the first group in the current matching
console.log(reg.test(str)); //=>true
console.log(RegExp. $1); //=>"1" Obtains the content matched by the first group in the current matching
console.log(reg.test(str)); //=>true
console.log(RegExp. $1); //=>"2" Obtains the content matched by the first group in the current matching
console.log(reg.test(str)); //=>false
console.log(RegExp. $1); //=>"2" stores the result of the last capture
RegExp.$1~RegExp.$9: obtain the information about the first to the ninth group after the current regular match
Copy the code
-2) Group naming (added in ES6)
It’s like giving names to groups
- Grammar:? < name >
- After the match, the information captured by the specified name group can be obtained based on the groups in the match result
reg = / ^ (? \d{6})(? \d{4})(?
\d{2})(?
\d{2})\d{2}(?
\d)(? :\d|X)$/
;
let res = reg.exec(str);
console.log(res.groups.A);
console.log(res.groups.E);
Copy the code
Here we do not explain, recommend a ruan Yifeng teacher ECMAScript 6 introduction inside the detailed explanation, small sesame is not here to teach a fish 😄
-3), the capture method of string and regular match — match
We have already mentioned this briefly, but here is the difference between match and ESec
match
andesec
The difference between
- 1. Set the global modifier
g
In case of:exec
Only one match can be captured per execution- The current result contains the result of large regular matches and small group matches
- If you want to capture all, you need to do this multiple times
match
One run captures all the information about the match- Only large regular matches do not contain information about small group matches
- 2. If no setting is required
g
In case of:- Only the first match is captured, and the results are the same (large re, small grouping included).
-4), the capture method of string and regular collocation — replace
Itself is the meaning of string substitution
- In the case of not using a regular, each execution
replace
Only one can be replaced, and many requirements cannot be solved without using re
let str = "xiaozhima@2019|xiaozhima@2020";
//=> Replace "xiaozhima" with "little sesame"
//1. Replace only one regular at a time
str = str.replace("xiaozhima"."Little Sesame").replace("xiaozhima"."Little Sesame");
console.log(str);
//2. It's easier to use regex
str = str.replace(/xiaozhima/g."Little Sesame");
console.log(str);
Copy the code
- Replace “jinse” with “jinsexiaozhima”
let str = "jinse@2019|jinse@2020";
//=> Replace "jinse" with "jinsexiaozhima"
str=str.replace("jinse"."jinsexiaozhima").replace("jinse"."jinsexiaozhima");
/ / "jinsexiaozhimaxiaozhima @ 2019 | jinse @ 2020" every replacement from string to find it the first position of (similar to the regular captured lazy)
Copy the code
let str = "jinse@2019|jinse@2020";
//=> Can be implemented based on the regular g
str = str.replace(/jinse/g."jinsexiaozhima");
Copy the code
Combined with regular:
- Syntax: STR = str.replace(reg,function)
- Features:
- 1. The regular and string are first captured for matching. Once the match is captured, the function is executed once
- 2, and the result of each capture (just like the result captured by ESEC) is passed to the function
- So you can use the residual operator to receive the result of each regular match
- Order of results: [large regular match, small group match, start index captured, original string……]
- 3. What is returned in the function is the same as what is returned in the original string with the result of a large regular match
Example: Processing time strings
//=> Require an argument to be passed in any format: xx-xx xx:xx; However, the corresponding index is 3:4:5 on January 2, year 0
String.prototype.formatTime = function formatTime(template) {
// 1. Obtain the year, month, day, hour, minute, and second information according to the time string of the operation
let arr = this.match(/\d+/g).map(item= > {
return item.length < 2 ? '0' + item : item;
});
// 2. Parse the formatted template, find the corresponding time, and replace the content in the template
template = template || '{0} year {1} month {2} day {3} hour {4} minutes {5} seconds';
return template.replace(/\{(\d+)\}/g, (_, group) => {
return arr[group] || "00";
});
};
let time = "The 2020-4-8 16:36:8";
time = time.formatTime('{0} year {1} month {2} day ');
console.log(time); //=> April 08, 2020
Copy the code
Example: Capitalize the first letter of a word
let str = "Good good study, day day up!;
let reg = /\b([a-zA-Z])[a-zA-Z]*\b/g;
//=> The function is executed six times, each time passing regular match information to the function
/ / = > every ARG: [" good ", "g"] [" good ", "g"] [" study ", "s"]...str = str.replace(reg,(... arg)=>{let [content,$1]=arg;
$1= $1.toUpperCase();
content=content.substring(1);
return $1+content;
});
console.log(str); //=>"Good Good Study, Day Day Up!"
Copy the code
Case: Dealing with URL parameters
// Get the parameter information in the URL (which may also contain the HASH value)
String.prototype.queryURLParams = function queryURLParams() {
let obj = {};
// Hash value processing
this.replace(/#([^?=#&]+)/g, (_, group) => obj['HASH'] = group);
// Question mark pass parameter information processing
this.replace(/([^?#=&]+)=([^?#=&]+)/g, (_, group1, group2) => {
obj[group1] = group2;
});
return obj;
};
let str = 'http://www.xxxxxxxxx.cn/?lx=1&from=weixin&name=xxx#video';
let obj = str.queryURLParams();
console.log(obj); //=> {HASH: "video", lx: "1", from: "weixin", name: "xxx"}
Copy the code
Case: realize the thousandth symbol processing
String.prototype.millimeter = function millimeter() {
return this.replace(/ \ d {1, 3} (? =(\d{3})+$)/g, value => {
return value + ', ';
});
};
let str = "2312345638";
str = str.millimeter();
console.log(str); / / = > "2312345638"
Copy the code