What is regular

Re is a powerful tool for searching and replacing strings. Regular expressions (called ‘regexp’ or ‘reg’) contain patterns and modifiers

How to create re and basic usage

There are two syntax for creating regular expression objects, one is through the constructor, the new operator, which allows you to dynamically construct patterns from a string, when the regular expression will change, or when you don’t know what pattern in advance, you can use the constructor to create it, right

let reg = new RegExp('ice ice')// Create the re with the condition inside the first ""
console.log('My heart belongs to Wang Bingbing.'.search(reg))// 5 Returns the index of ice ice
Copy the code

The other is the literal method, which is created with a slash ‘/’. The slash ‘/’ will tell JS that we are creating a re. When we know what mode to use and it will not change, we can create the re with the literal method

let reg=Ice ice / // Creates the re, '/ condition /' in the middle of the skew bar is the condition
console.log('My heart belongs to Wang Bingbing.'.search(reg)) //5 Returns the index of ice ice
Copy the code

Special character character classes

The two simple little 🌰 above is an accurate match, we know who is, can create, but sometimes, we match is an uncertain character but know what type of time to do, for example, we come to find Bing Bing’s mobile phone number, ‘Wang Bing Bing’s mobile phone number is: 18888888888’, then I need to get ‘18888888888’, at this point the special character is used, we know the phone number is 0-9, then we can use \ D to get the number,

let reg=/\d/ // Create a re,
console.log('Wang Bingbing's mobile number is: 18888888888'.match(reg)) 
//["1", index: 9, input: "groups: undefined"]
// We see the first output ['1'] which is the result of our match
// index represents the index of the result
// Input represents what we are entering
// groups Indicates the group name
Copy the code

‘18888888888’ is what we want. Don’t worry, we need to get one \d, we need to get multiple \d+

let reg=/\d+/ // Create a re,
console.log('Wang Bingbing's mobile number is: 18888888888'.match(reg)) 
// ["18888888888", index: 9, input: "groups: undefined] // [" 1888888888888 ", index: 9, input:" Groups: undefined]
Copy the code
Special characters role
d Matching numbers 0-9 is equivalent to [0-9]
D Matches a non-numeric character
w Matching a single-word character (letter, digit, underscore) is equivalent to [A-za-z0-9_]
W Matches a non-single-word character except (alphanumeric, underscore equivalent) [^ A-za-z0-9_]
s Matches a whitespace character, including a space, TAB, page feed, or line feed
S Matches a non-whitespace character
\ A backslash before a non-special character indicates that the next character is a special character, which cannot be interpreted literally. A backslash before a non-special character indicates that the character is escaped\ \The representation is a\
^ Represents the beginning of the matching input,/^A/It won’t match ‘A’ in “an A”, but it will match ‘A’ in “an E”.
$ Represents the end of matching input,/t$/It won’t match the ‘t’ in “Eater”, but it will match the ‘t’ in “eat”.
* Matches 0 or more times of the previous expression
+ Matches the previous expression 1 or more times
? Matches 0 or 1 of the previous expression,/e? le? /Match ‘el’ in ‘angel ‘, ‘le’ in’ Angle ‘and’ L ‘in’ Oslo ‘ifFollow any quantifier, +,? Or after {}* will change the quantifier toNon-greedy ** (match as few characters as possible), and default usedGreed mode(matches as many characters as possible) just the opposite. For example, use “123abc”/\d+/Will match “123” while using/\d+? /It only matches “1”
. Matches all single characters except newline characters
let reg=/^a? \d+$/ // Create a re that can start with a letter and end with a number
console.log('a18888888888'.match(reg)) 
// ["a18888888888", index:0, input: "a18888888888", groups: undefined]
console.log('18888888888'.match(reg)) 
// ["18888888888", index: 0, input: "18888888888", groups: undefined]
// Match a QQ mailbox
let email = '[email protected]'
let reg = /^\d+@\w+\.com$/;
console.log(email.match(reg));// ["[email protected]"]
Copy the code

Special character symbol class

In the qq mailbox example above, if not com end but cn at the end of it, then how to match, then can use | said or

// Match a QQ mailbox
let email = "[email protected]";
let email2 = "[email protected]";
let email3 = "[email protected]";
let reg = /^\d+@\w+(\.\w+)+\1? /;
let reg1 = /^\d+@\w+\.(com|cn)$/;
console.log(email.match(reg1)); // ["[email protected]", ".com"]
console.log(email2.match(reg)); // ["[email protected]", ".cn"]
console.log(email3.match(reg)); // ["[email protected]", ".cn"]
Copy the code
Special characters role
| X | y match ‘x’ or ‘y’.
(a) (x)Capturing parenthesesIt will match ‘x’ and remember the matches, in /(f)(b)\1\2/ \1 represents f,\2 represents B, and in regular expression substitutions $1 can be used to represent the original string
{n} N is a positive integer that matches the number of occurrences of the preceding character
{n,} N is a positive integer that matches the preceding character at least several times
{n,m} Both n and m are integers. Matches the preceding character at least n times and at most m times. If the value of n or m is 0, the value is ignored
[xyz] A collection of characters that match any of the characters in [] and can be used-To pick a range [0-9]
[^xyz] A collection of characters that matches any character not contained in square brackets
// Match a mobile phone number with 11 digits starting with super 13, 15, 17, and 18
let tel = "18787875678";
let tel1 = "12787875678";
let reg = / ^ 1,5,7,8 [3] \ d {9} $/;
console.log(tel.match(reg)); / / / "18787875678"
console.log(tel1.match(reg)); //null
// Matches the first four digits of a landline number - the link is followed by 7 or 8 digits
let tel = "0100-89087678";
let tel1 = "010-89087678";
let reg = / ^ \ d {3, 4} - \ d {7, 8} $/;
console.log(tel.match(reg)); / / / "0100-89087678"
console.log(tel1.match(reg)); / / / "010-89087678"
Copy the code

methods

We’ve been using the match method up here, which returns an array and returns NULL if there’s no match. There are other ways

methods describe
exec Executes the RegExp method to find a match, which returns an array (or null if no match is found).
test A RegExp method that tests a match in a string and returns true or false.
match A String method that performs a lookup on a String, returning an array and null if there is no match.
matchAll A String method that finds all matches in a String and returns an iterator
search A String method that tests a match in a String, returning the position of the match, or -1 if there is none
replace A String method that looks for matches in a String and replaces matched ones with replacement characters
split One uses a regular expression or a fixed string to separate a string and stores the delimited substring in an arrayStringmethods
let tel = "0100-89087678";
let tel1 = "010-89087678";
let reg = / ^ \ d {3, 4} - \ d {7, 8} $/;
console.log(reg.exec(tel1)); / / / "0100-89087678"
console.log(reg.test(tel)); //true
console.log(tel.match(reg)); / / / "0100-89087678"
console.log(tel.search(reg)); / / 0
console.log(
tel.replace(reg, function () {
return "*".repeat(10); }));/ / * * * * * * * * * *
Copy the code

Advanced search

Regular expressions have six optional arguments (flags) to allow global and case-insensitive searches, etc. These parameters can be used alone or together in any order and are included in the regular expression instance.

methods describe
g Global search
i Case insensitive
m Multi-line matching
s Match newline character
u Matches using patterns of Unicode codes.
y Perform “Stickiness (sticky) “and matches from the current position of the target string
let str = "This this this";
let reg1 = /t/i; // Match t is case insensitive
let reg2 = /t/g; // Global match t
let reg3 = /t/gi;  // Global matching t is case insensitive
console.log(str.match(reg1)); // ['T']
console.log(str.match(reg2)); // ["t", "t"]
console.log(str.match(reg3)); // ["T", "t", "t"]
    
Copy the code

Assertions to find

methods describe
x(? =y) Matching ‘x’ only if it is followed by ‘y’ is called antecedent assertion
(? <=x)y Matching ‘x’ with only ‘y’ at the front is called a trailing assertion
x(? ! y) Matching ‘x’ only if it is not followed by ‘y’ is called positive negative lookup
(? <! x)y Matching ‘x’ only with no ‘y’ at the front is called reverse negative lookup
// Hide the phone number
let tel = "18787875678";
let reg = / (? <=\w{3})\w+(? =\w{4})/; 
tel.replace(reg, () = > {
  return "*".repeat(4);
});
/ / "187 * * * * 5678"
Copy the code