This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
Common regular expressions
- Verifies whether it is a significant number
- Rule analysis
- It may or may not have a + –
- One digit from 0 to 9 can be used, but the first digit of multiple digits cannot be 0
- You may or may not have a decimal part, but you have to have a decimal point followed by a number
let reg = / ^ (+ -)? (\d|([1-9]\d+))(\.\d+)? $/;
Copy the code
- Verify password
- Numbers, letters, and underscores
- 6 to 16
let reg = /^\w{6, 16}$/;
Copy the code
- Verify real name
- Chinese characters / ^ $/ [\ u4E00 – \ u9FA5]
- The length of the 2 ~ 10
- There may be translated names and Chinese characters
let reg = / ^ [\ u4E00 - \ u9FA5] {2, 10} (· [\ u4E00 - \ u9FA5] {2, 10})} {0, 2 $/
Copy the code
- Validation email
let reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
Copy the code
- Id Card Number
- A total of 18
- The last digit might be X
- The top six id numbers: provinces and counties
- Middle 8 bits: date of birth
- Last digit: X or number
- Second to last: even: female, odd: male
- The rest is algorithmically calculated
// The second function of the parentheses is group capture, which can not only capture the information of the large re match, but also capture the content of each small group individually
let reg = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{2}(\d)(\d|X)$/
Copy the code
Capture of re
- A method to achieve regex capture
- Method on RegExp. Prototype
- exec
- test
- String. Prototype supports regular expression handling
- replace
- match
- splite
let str = "Alvin2019yangfan2020qihang2021";
let reg = /\d+/
Copy the code
- The capture of the re is implemented based on exec
- The result is either NULL or an array
- The first item is the contents of this capture
- Other items: Contents captured separately for the corresponding subgroup (contents matched in the braces)
- Index: Start index of the current captured content in the string
- Input: original string
- Exec can only catch one match per execution of the regex rule, but by default, no matter how many times it is executed, the result is the first match and the others are not caught
- The laziness of re capture
Lazy regex: The default catches the first one. The reason for laziness is that by default, lastIndex is not changed, and is always looked up from the beginning of the string.
- The re can be modified with the g (global match) modifier so that the lastIndex value automatically changes
- The lastIndex value will return to 0 when the capture is complete
- The re has a lastIndex attribute reg.lastIndex, which represents the starting index position of the next match of the current re (default: 0).
- LastIndex does not change after the first match is captured, so the next exec still looks at the beginning of the string, so it always finds the first match
/* * Demand: Since exec can only capture data once at a time, you need to write an execAll, which can be executed once to capture all matched data (provided that the global modifier g must be set for the re) * the match method in the string can be executed once to capture all matched data (provided that the global modifier G also needs to be set) */
~ function(){
function execAll(str = ""){
// Verify that the global modifier g is set for the current regex, otherwise forever catching the first will cause an infinite loop
if(!this.global) return this.exec(str);
// STR is the string to match
// This: instance of RegExp (current re)
let ary = [],// Stores the final capture
res = this.exec(str);// The contents of each capture
while(res){
ary.push(res[0]);
res = this.exec(str);
}
return ary;
}
RegExp.prototype.execAll = execAll; } ();let reg = /\d+/g
console.log(reg.execAll(str));
Copy the code
- Group capture of re
// Take id number as an example:
let str = "130828199001061235"
let reg = /^(\d{6})(\d{4}(\d{2})(\d{2})\d{2}(\d)(\d|X))$/;
console.log(reg.exec(str));
console.log(str.match(reg));
Copy the code
- The first result: the result of the grand re match
Other items: Each small group matches the captured results separately. If the group is set (change priority), but the capture does not need to be captured separately, it can be based on:? : to process (matches only capture) reg = / ^ (\ d {6}) (\ d {4} (\ d {2}) (\ d {2}) \ d {2} ((\ d)? :\d|X))$/;
- If g value is not set to match once, exec and match will obtain the same result (both large regex match information and small group match information).
However, if the global modifier G is set, that is, in the case of multiple matches, match can only obtain the matched content of the large regular, but the information of small groups cannot be obtained, and the acquisition needs to be executed for multiple times
STR = “{0} year {1} month {2] day “; reg = /{\d+}/
- Third use of grouping: “grouping reference”
- Group reference: it is to use “\ number” to make its representation and the corresponding group appear exactly the same content
str = “book”; // Good, look, moon… Reg = /^ [a-za-z]([a-za-z])\1[a-za-z]$/; // \1
- Cupidity of regular capture
- Greedy for re capture: By default, re capture is based on the longest result matched by the current re
For example, /\d+/g is a regular that matches 1 to more than one digit, which means that one digit is ok, and two digits are ok, but when we match “abc2020de” as a string, we will find that the first match matches all of 2020, instead of a 2 and then a 0… Such is the cupidity of regular matching.
- Set after the quantifier metacharacter? , will cancel the cupidity of capture (install the shortest result of the re match to match)
- Five functions of question mark in regularization
- To the left of the question mark is a non-quantifier metacharacter: a self-dial quantifier metacharacter occurs zero to once
- To the left of the question mark is the quantifier metacharacter: ungrabbility
- (? 🙂 matches only but does not capture
- (? =) Forward check
- (? !). Negative lessons
- Other methods of re capture
- Test itself is used for regular matching, but it can also be captured
- Regexp. 1 RegExp1 to RegExp1 RegExp9: obtains information about the first to ninth groups after the current re match
let str = "{0} Year {1} Month {2} day";
let reg = /\{(\d+)\}/g;
console.log(reg.test(str));//true
cosole.log(RegExp. $1);/ / 0
Copy the code
- The method of implementing a replacement in the replace string (typically used with a re)
- Replace all Alvin in the string with Hello
- Because the string’s replace method can only replace one at a time, it needs to be called twice, or multiple times if it’s replacing multiple strings
- Here we can use the re in conjunction to achieve a full substitution
let str = "Alvin@2019|Alvin@2020";
let reg = /Alvin/g
str.replace(reg, "Hello");
Copy the code
- An example of replace with a re: Processing time strings
Plan a
let str = "2019-08-13";// Changed to August 13, 2019
let reg = / ^ (\ d {4}) - (\ d {1, 2}) - $/ (\ d {1, 2});
/ / a
let time = str.replace(reg, "$1 year $2 month $3");
console.log(time);
Copy the code
- Replace ([reg],[function])
- First, use reg and time to match the capture, can match a few times will pass the function to execute several times, and is a match on the execution
- Not only does replace execute the method, but it also passes the argument information to the method (the same information that exec captures: the contents of the large re match and the contents of the small grouping match).
- Replace the matching content with whatever is returned in the function
time = str.replace(reg, (all, $1, $2, $3) = >{
console.log($1, $2, $3);
return $1 + "Year" + $2 + "Month" + $3 + "Day"
});
Copy the code
- Capitalize the first letter
let str = "good good study, day day up!";
let reg = /\b([a-zA-Z])[a-zA-z]*\b/g; // \b indicates word boundaries
str = str.replace(reg, (. arg) = >{
let [word, $1] = arg;
$1 = $1.toUpperCase();
word = word.substring(1);
return $1 + word;
})
console.log(str);
Copy the code