current position:Home>Dry goods | regular application (actual combat summary)

Dry goods | regular application (actual combat summary)

2021-08-27 10:07:06 Weibo front end

See everyone playing Nuggets I also github Copy and send an article If useful Support a lot

Regular applications ( summary )

1. Common business examples

Common business ( user name , Password strength, etc , There is no list of , Search a lot .), You can also see what I summarized 《 Regular expressions commonly used in front-end form validation 》

1.1 User name regular

// User name regular ,4 To 16 position ( Letter , Numbers , Underline , minus sign )
var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
// Output  true
console.log(uPattern.test("caibaojian"));
// The strength of the password must be a combination of upper and lower case letters and numbers , Special characters cannot be used , The length is in 8-10 Between .

var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,10}$/;

 Copy code 

2. Regular grouping

Regular expressions are character by character to match , So if you want to match a word, such as is , Just have to write /is/, If you want to match is appear 3 Time , You can only write /isisis/, We want to use quantifiers /is{3}/, But this only means s appear 3 Time , How can I modify it to express is Three times , hold is Enclosed in brackets ,/(is){3}/. Put... In parentheses is Cover up , It means that it is a whole , A group , They will appear together , It's a successful match , So it's called grouping . Grouping has an important concept , It's quoting , When there are groups in a regular expression , We can get the content of the group , How to get , Namely $n, n Representation number ,$1 Represents the content of the first group ,$2 Represents the content of the second group ,$3 Represents the content of the third group , By analogy , In fact, there is another $0, It's more special , So list it separately , It said , The entire regular expression matches the successful content

2.1 Example ( If the telephone number is hidden in the middle )

//  Example 1
var reg=/(\d{3})\d{4}(\d{4})/;
var phone="13423874592";
console.log( phone.replace(reg,("$1****$2")));//134****4592

//  Example 2: The hump changes into a middle line 
'fooBarBaz'.replace(/([A-Z])/g,"-$1").toLowerCase() // foo-bar-baz

//  Example 3
let reg = /(\d{4})-(\d{2})-(\d{2})/g;
let string = '2017-03-20'
let replaceString = string.replace(reg,"$2/$3/$1");
console.log(replaceString)  // 03/20/2017

//  Example 4
let reg = /(\d)2\1/g;
let string = '121 222 323 424'
let replaceString = string.replace(reg,'X');
console.log(replaceString)  // X X X X
 Copy code 

3. Add variables

// http://blog.csdn.net/icanlove/article/details/39499777
var v = "bl";

var re =new RegExp("^\d+" + v + "$","gim"); // re by /^\d+bl$/gim

// thus , The original problem has been completely solved .

// in addition , Another way is to use eval A method of dynamically executing a string , But I think from all aspects , It's all bad policy .

var re = eval("/^\d+" + v + "$/gim")
 Copy code 

4. string Of replace

Find a regular string , Just replace it with the corresponding string . Return the content after replacement

usage : String.replace( Regular , New string / Callback function )( In the callback function , The first parameter refers to the characters that match successfully every time )

Example : Sensitive word filtering , such as ” I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square “.------ I love *****,*** The sun rose on the . namely ( Beijing and Tiananmen become Number ),

At first we might think of such a method :

var str = " I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square .";
var re = / Beijing | The tiananmen square /g; //  Find Beijing   Or tiananmen square   The global matching 
var str2 = str.replace(re,'*');
alert(str2) // I love **,* The sun rose on the 
// This just turns what you find into a *, Not just a few words *.
 Copy code 

If you want to realize that a few words correspond to several *, We can use callback function to realize :

var str = " I love tian 'anmen square in Beijing , The sun rises over tian 'anmen square .";
var re = / Beijing | The tiananmen square /g; //  Find Beijing   Or tiananmen square   The global matching 
var str2 = str.replace(re,function(str){
console.log(str); // For testing : The first parameter of the function represents the regular characters found each time , So the first time str I mean Beijing   The second time str Is the tiananmen square   third time str Is the tiananmen square 
var result = '';
for(var i=0;i<str.length;i  ){
result  = '*';
}
return result; // So when you find a few words, you return a few *
});
console.log(str2) // I love *****,*** The sun rose on the 
 Copy code 

The whole process is , Find Beijing , Replaced with two *, Find Tiananmen Square and replace it with 3 individual *, Find Tiananmen Square and replace with 3 individual *.

var arr = {
    content: " Hello #D12345#,hello#D321#world",
    lawitems: {
        "D12345": "aaaa",
        "D321": "bbbbb"
    }
}

arr.content = arr.content.replace(/#([^#]+)#/g, function (match, $1) {
    return arr.lawitems[$1]||match;// Not in the lawitems Find and return the original string 
})
// " Hello aaaa,hellobbbbbworld"
 Copy code 

replace Is a very useful method , Often used .

5. Boundary class (boudary)

The boundary class mainly uses four : ^ To begin with ,$ What does it end with , boudary Show word boundaries ,B Indicates a non word boundary . The boundary is where words are separated from words , The most obvious is the space .

Writing an example can be more intuitive .

let reg = /is/g;
let string = 'this is a dog '
let replaceString = string.replace(reg,"IS");
console.log(replaceString)  // thIS IS a dog
 Copy code 

Two is All replaced , This is in line with expectations . But how can we just replace the middle is, In the middle of the is There is a feature , It's a word , Because there are spaces in front and behind , Makes it separate from other words , Because there are spaces is To become a word , So spaces are word boundaries , \b Can match it . Change the regular expression to /\bis/g, You can see the output this IS a dog, Only match the second . What if you just want to change the first one ? That's good to do , Because the first one is Contained in a word , So it's not preceded by a word boundary , Direct change to B That's all right. , Change the regular expression to /Bis/g That's all right. .

Hump turn -

const hyphenateRE = /\B([A-Z])/g
const str = 'LiuWeiBo'
str.replace(hyphenateRE, '-$1').toLowerCase() // liu-wei-bo
 Copy code 

6. Regular assertion

Assertion , Match only one location , For example, look at the following example

//  such as , You want to match a “ people ” word , But you just want to match the Chinese characters , People who don't want to match the French can use the expression 
/(?<= China ) people /
//  therefore , Expressions can only work when used in conjunction with other wildcards .
/(?=.*[a-z])\d/
//  This is just saying   Match with “ Any character followed by a lowercase letter ” Number at the beginning , Match only numbers .
 Copy code 
//  Example 1
String(123456789).replace(/(\d)(?=(\d{3})+$)/g, "$1,");
// or
'123456789'.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
//  The result is :123,456,789

//  Example 2: Integers and decimals are compatible 
'1234567890030.7890'.replace(/(?=\B(?:\d{3})+\b)(\d{3}(.\d+$)?)/g,',$1');
 Copy code 

6.1 (?=pattern) Forward assertion

Represents a position in a string , The character sequence immediately after this position can match pattern

For example a regular expression This string , To match regular Medium re, But can't match expression Medium re, It can be used re(?=gular), The expression qualifies re On the right , This position is followed by gular, But it doesn't consume gular These characters , Change the expression to re(?=gular)., Will match reg, Metacharacters . Match the g, The weight of brackets matches e and g Position between .

6.2 (?!pattern) Negative antecedent assertion ( Negative pre check , Non-fetch match )

Represents a position in a string , The character sequence immediately after this position cannot match pattern

For example regex represents regular expression This string , To match, divide regex and regular In addition to the re, It can be used re(?!g), The expression qualifies re On the right , This position is not followed by a character g. The difference between negative and positive , It depends on whether the character after this position can match the expression in parentheses .

//  Will not match to contain  df The content of 
var reg = /^(?!.*df).*$/     // df It's a string you don't want to match .
reg.test('[email protected]') // true

var str = `[email protected] [email protected] [email protected] [email protected]`

reg.test(str) // false
 Copy code 

6.3 (?<=pattern) Forward and backward assertions

Represents a position in a string , The character sequence immediately before this position can match pattern ES6+ Support post assertion

For example regex represents regular expression This string , Yes 4 Word , To match the inside of a word re, But it doesn't match the beginning of the word re, It can be used (?<=\w)re, Inside the word re, stay re It should be preceded by a word character . That's why it's called late assertion , Because the regular expression engine matches strings and expressions , Is to scan the characters in the string one by one from the front to the back , And judge whether it conforms to the expression , When the assertion is encountered in an expression , The regular expression engine needs to detect the scanned characters at the front of the string , It is backward relative to the scanning direction .

6.4 (?<!pattern) Negative hindrow assertion

Represents a position in a string , The character sequence immediately preceding this position cannot match pattern. ES6+ Support post assertion

For example regex represents regular expression This string , To match the beginning of a word re, It can be used (?<!\w)re. At the beginning of the word re, In this case , That is, not inside the word re, namely re Not preceded by word characters . You can also use it \bre To match .

7. Multi-line matching

^ and $ Well understood. , /^T/ In capital letters T At the beginning , /T$/ In capital letters T At the end , Pay attention to their writing position , One in front of , One in the back . If there is a newline character in the string , let string = '@123 @456 @789', The string behaves as if it had three lines . Here are chrome Output in browser

At this time, if /^@/g To match , It will only match the first @,


let reg = /^@/g;
let string = `@123 @456 @789`
let replaceString = string.replace(reg,"X");
console.log(replaceString)
/* * X123 * @456 * @789 */
 Copy code 

If you want to match three , Then you need to use m Modifier , Multiline identifier , It means that if there is a newline character in the string , Think of strings as multiple lines .m Identifier , Only in regular expressions ^ or & It works when , This is also the handle. m The reason why the identifier is put here .

More dry goods and high-quality articles move forward : weibozzz.github.io/

copyright notice
author[Weibo front end],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827100658897c.html

Random recommended