当前位置:网站首页>JS regular - comb
JS regular - comb
2022-06-21 09:59:00 【South wind number】
One 、 How it was created
- Literal : Regular expressions are placed directly in / / In :
const rex = /pattern/;
- Constructors :RegExp Object represents an instance of a regular expression :
const rex = new RegExp("pattern");
One big difference between these two methods is that the constructor of the object allows you to pass quoted expressions , In this way, regular expressions can be created dynamically .
Created by these two methods Regex Objects have the same methods and properties :
let RegExp1 = /a|b/
let RegExp2 = new RegExp('a|b')
console.log(RegExp1) // Output results :/a|b/
console.log(RegExp2) // Output results :/a|b/
Two 、 Pattern matching
1. Character set
If we want to match bat、cat and fat What to do with this type of string ? You can do this by using character sets , use [] Express , It will match any character it contains . You can use /[bcf]at/ig:
2. character in range
If we want to match all in the string with at Ending words , The most direct way is to use the character set , And provide all the letters in it . For such characters in a range , You can directly define the character range , use - Express . It is used to match any character in the specified range . You can use /[a-z]at/ig:
Common ways of using the scope are as follows :
- Part of the scope :[a-f], matching a To f Any character of ;
- Lower case range :[a-z], matching a To z Any character of ;
- Upper case range :[A-Z], matching A To Z Any character of ;
- The range of numbers :[0-9], matching 0 To 9 Any character of ;
- Symbol scope :[#$%&@];
- Mixing range :[a-zA-Z0-9], Match all numbers 、 Any character in upper and lower case letters .
3. Quantity character
If you want to match a three letter word , According to the character range we learned above , You can write like this :
[a-z][a-z][a-z]
Here we match the three letter word , If you want to match 10 individual 、20 A letter word ? Do you want to write the scope one by one ? A better way is to use curly braces {} To express , See example :
You can see , Here we've matched all the consecutive 5 Four letter words ( Including more than 5 Four letter words , But it will only match to the front 5 Letters ).
In fact, the complete syntax for matching repeated characters is as follows :{m,n}, It will match the previous character at least m Times at most n Secondary repetition ,{m} Represents a match m Time ,{m,} At least m Time .
therefore , When we give 5 When followed by a comma , It means at least five matches :
So here we have all the consecutive matches 5 Or 5 More than words .
When the number of matches is at least 4 Time , at most 5 When the time , The results are as follows :
In addition to using braces to match a certain number of characters , There are three related patterns :
- +: Match the previous expression one or more times , amount to {1,};
- *: Match the previous expression 0 Times or more , amount to {0,};
- ?: Use it alone to match the previous expression zero times or once , amount to {0,1}, If followed by a quantifier *、+、?、{} Later, the quantifier will be changed into a non greedy mode ( Match as few characters as possible ), The default is to use greedy mode .
Let's take a simple example , The regular expression we match here is /a+/ig, give the result as follows :
It and /a{1,}/ig The matching result is the same :
Use /[a-z]+/ig You can match pure alphabetic words of any length :
4. Metacharacters
Using metacharacters, you can write more compact regular expression patterns . Common metacharacters are as follows :
- \d: amount to [0-9], Match any number ;
- \D: amount to [^0-9];
- \w: amount to [0-9a-zA-Z], Match any number 、 Case letters and underscores ;
- \W: amount to :[^0-9a-zA-Z];
- \s: amount to [\t\v\n\r\f], Match any whitespace , Including Spaces , Horizontal tabs \t, Vertical tabs \v, A newline \n, A carriage return \r, Page identifier \f;
- \S: amount to [^\t\v\n\r\f], Indicates a non blank character .
Let's take a simple example :
Use here \d To match any number 、 Letters and underscores . Here is the match 7 Four consecutive characters .
5. Special characters
You can write more advanced schema expressions using special characters , Common special characters are as follows :
- .: Matches any single character except the newline character ;
- \: Mark the next character as a special character 、 Or literal character 、 Or back reference 、 Or octal escape character ;
- |: Logic or operator ;
- [^]: Take the , Match any character not included .
Let's take a simple example , If we use /ab*/ig Match , The results are as follows :
Then we just want to match * What do I do ? You can use \ Escape it :
This will only match ab* 了 .
Or matching is simple , See example , The matching rule is :/ab|cd/ig, The results are as follows :
This will match all the... In the string ab and cd character . If you want to match sabz perhaps scdz Well ? The beginning and the end are the same , Only the middle two characters are optional . In fact, you only need to add parentheses to the middle or part :
Use irregular rules in the scope , See example :
All non alphabetic characters are matched here .
6. Position matching
If we want to match words that end with certain characters in a string , How can words that begin with certain characters be implemented ? Regular expressions provide methods to match characters by position :
- \b: Matches a word boundary , That is, the position between the word and the space ;
- \B: Match non word boundaries ;
- ^: Match the beginning , Match the beginning of a line in a multiline match ;
- $: Match the end , Match the end of a line in a multiline match ;
- (?=p): matching p Front position ;
- (?!=p): Matching is not p Front position .
The most common is to match the start and end positions . Let's first look at the matching of the starting position , Use here /^ex/igm To match multiple rows with ex Beginning line :
Use /e$/igm To match to e The line at the end :
have access to \w+$ To match the last word on each line :
We need to pay attention to , Here we all use m Modifier turns on multiline mode .
Use /(?=the)/ig To match the string the Position of the front face :
We can use \b To match word boundaries , The matching results are as follows :
It can be hard to understand , We can use the following regular expression to match the complete word :\b\w+\b, The results are as follows :
3、 ... and 、 Modifier
Common modifiers for regular expressions are as follows :
- g: Represent global mode , It is applied to all strings ;
- i: Indicates case insensitive , That is, the case of the string is ignored when matching ;
- m: For multiline mode , mandatory $ and ^ Match each newline character separately .
These modifiers are always used after the last forward slash , Can be used together . Let's take a look at the functions of these modifiers .
In the first example , There are two... In the string “ It's about ”, But only one was matched . This is because the regular expression matches the first qualified character by default . If you want to match all the matching characters , You can use g Modifier :
/ It's about /g
This will match all the characters that meet the criteria :
When you need to match the quoted English string , And ignore the letter case of the string ,i Modifiers come in handy .
/a/gi

There's also a little question , If the object constructor is used to construct the regular expression, it makes , How to add these modifiers ? It's very simple , Just pass the modifier as the second parameter to Constructor is OK :
let regExp = new RegExp('[2b|^2b]', 'gi')
console.log(regExp) // Output results :/[2b|^2b]/gi
Four 、RegExp example
1. Example method
RegExp The instance is set to test() and exec() These two methods are used to verify regular expressions . Let's take a look at these two methods respectively .
(1)test()
test() Used to detect whether a string matches a pattern , If the string contains matching text , Then return to true, Otherwise return to false.
const regex1 = /a/ig;
const regex2 = /hello/ig;
const str = "Action speak louder than words";
console.log(regex1.test(str)); // true
console.log(regex2.test(str)); // false
(2)exec()
exec() Used to retrieve the matching of regular expressions in strings . This function returns an array , It stores the matching results . If no match is found , The return value is null.
const regex1 = /a/ig;
const regex2 = /hello/ig;
const str = "Action speak louder than words";
console.log(regex1.exec(str)); // ['A', index: 0, input: 'Action speak louder than words', groups: undefined]
console.log(regex2.exec(str)); // null
When used in global regular expressions exec when , It will return every other time null, Pictured :
What's going on here ?MDN Is explained as follows :
To solve this problem , We can run each exec The order will be lastIndex The assignment is 0:
2. Instance attributes
RegExp The instance also has some built-in properties , These properties let you know all aspects of a regular expression , But it's not very useful .
| attribute | describe |
|---|---|
| global | Boolean value , Indicates whether... Is set g sign |
| ignoreCase | Boolean value , Indicates whether... Is set i sign |
| lastIndex | Integers , Indicates the character position at which to start searching for the next match , from 0 Count up |
| multiline | Boolean value , Indicates whether... Is set m sign |
| source | String representation of regular expressions , Significant string pattern matching in literal form rather than in the passed in constructor |
5、 ... and 、 String method
stay JavaScript There is 6 One common method is to support regular expressions , Let's take a look at these methods .
1. search()
search() Method to retrieve the substring specified in the string , Or retrieve the substring that matches the regular expression , And returns the starting position of the substring . If no matching substring is found , Then return to -1.
const regex1 = /a/ig;
const regex2 = /p/ig;
const regex3 = /m/ig;
const str = "Action speak louder than words";
console.log(str.search(regex1)); // Output results :0
console.log(str.search(regex2)); // Output results :8
console.log(str.search(regex3)); // Output results :-1
You can see ,search() Method will only return the index value of the first character that matches , When no corresponding value is matched , It will return -1.
2. match()
match() Method to retrieve the specified value in a string , Or find a match for one or more regular expressions . If no matching text is found , match() Will return null. otherwise , It will return an array , It holds information about the matching text it finds .
const regex1 = /a/ig;
const regex2 = /a/i;
const regex3 = /m/ig;
const str = "Action speak louder than words";
console.log(str.match(regex1)); // Output results :['A', 'a', 'a']
console.log(str.match(regex2)); // Output results :['A', index: 0, input: 'Action speak louder than words', groups: undefined]
console.log(str.match(regex3)); // Output results :null
You can see , When there is no g When it comes to embellishments , You can only perform a match once in a string , If you want to match all the values that meet the criteria , You need to add g Modifier .
3. matchAll()
matchAll() Method returns an iterator containing the results of all matching regular expressions and the group capture group . Because the return is the ergodic , So we usually use for…of Cycle out .
for (const match of 'abcabc'.matchAll(/a/g)) {
console.log(match)
}
//["a", index: 0, input: "abcabc", groups: undefined]
//["a", index: 3, input: "abcabc", groups: undefined]
We need to pay attention to , The first argument to this method is a regular expression object , If the parameter passed is not a regular expression object , Will implicitly use new RegExp(obj) Convert it to a RegExp . in addition ,RegExp The global mode must be set g In the form of , Otherwise, an exception will be thrown TypeError.
4. replace()
replace() Used to replace some strings with others in a string , Or replace a substring that matches a regular expression .
const regex = /A/g;
const str = "Action speak louder than words";
console.log(str.replace(regex, 'a')); // Output results :action speak louder than words
You can see , The regular expression in the first argument matches the first upper case of the string A, And replace it with the lowercase... In the second parameter a.
5. replaceAll()
replaceAll() Method is used to replace some characters with others in a string , Or replace a substring that matches a regular expression , This function will replace all matching substrings .
const regex = /a/g;
const str = "Action speak louder than words";
console.log(str.replaceAll(regex, 'A')); // Output results :Action speAk louder thAn words
We need to pay attention to , When using a regex when , You must set the global (“g”) sign , otherwise , It will trigger TypeError:“ Global... Must be used RegExp call replaceAll”.
6. split()
split() Method is used to split a string into an array of strings . Its first argument is a string or regular expression , Split the string from the place specified by this parameter .
const regex = / /gi;
const str = "Action speak louder than words";
console.log(str.split(regex)); // Output results :['Action', 'speak', 'louder', 'than', 'words']
there regex To match an empty string , So the string is finally broken into an array at each space in the string .
6、 ... and 、 The practical application
1. Match the password
Check the format of the password , It contains at least one capital letter 、 Lowercase letters 、 Numbers 、 Symbol , The length is 8-12 position :
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,12}$/g
Here we mainly use the forward looking in regular expressions , The forward-looking syntax is (?=pattern), That is, there must be... At the corresponding position of the target string pattern Part of the match , But not as a matching result , It will not be stored in the buffer for future use . Let's take a look at the meaning of each part of this regular expression :
- (?=.*[a-z]): Matches any character followed by a lowercase letter ;
- (?=.*[A-Z]): Matches any character followed by a capital letter ;
- (?=.*\d): Match any character followed by a number ;
- (?=.*\W): Matches any character followed by a symbol ;
- .{8,12}: The matching length must be at least 8 Characters , At most 12 Characters .
^ and $ You can guarantee that the match is made from the beginning to the end of the string , That is, only the entire password is matched , Do not consider partial matching .
Here are the test results :
2. Match mailbox
Check the email address :
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:\.[ a-zA-Z0-9-]+)*$/g
Let's take a look at the meaning of each part of this regular expression :
- [a-zA-Z0-9.!#$%&'*+/=?_~-]+: Check that all valid characters are used and at least one is present ( Last +` Used to check whether there is at least one character );
- [a-zA-Z0-9-]+: This section is used to verify that the hostname is valid , Host names can be upper and lower case letters 、 Numbers 、 The middle horizontal line . final + Indicates that there is at least one ;
- (?:.[a-zA-Z0-9-]+)*: This section is an optional domain name suffix , the * It means that the preceding character is 0 One or more , such .com、.com.cn And other domain names can be matched to ;
- ^ and $ You can guarantee that the match is made from the beginning to the end of the string , That is, only the entire mailbox string is matched , Do not consider partial matching .
Here are the test results :
3. Match the Numbers
Check whether the number is an integer :/^\d+$/, among \d+ Indicates that there is at least one digit . The test results are as follows 
Check whether the number is decimal :/^\d*.\d+$/, among \d* Means at least 0 Digit number ,. Is to escape the decimal point ,\d+ It means that there is at least one decimal place . The test results are as follows :
Check whether a number is an amount :/^\d+(.\d{2})?$/
7、 ... and 、 Online regular website
https://regex101.com/ Online regular
https://regexr.com/ Online regular
https://www.regexpal.com/ Online regular
https://regex-vis.com/ Online regular
vscode plug-in unit Regex previewer

边栏推荐
- Equals and hashcode
- Introduction and template of segment tree Foundation (I)
- [practice] STM32 FreeRTOS migration series tutorial 5:freertos message queue
- New programmers optimize a line of code on Monday and are discouraged on Wednesday?
- 基因型填充前的质控条件简介
- Get the data in the configuration file properties
- Electron checks the CPU and memory performance when the module is introduced
- Vuforia引擎支持的版本
- R language uses the names function to modify the name of the data column variable, modify the name of the specified data column, and maintain the original data column name for the unmodified data colu
- DSP online upgrade (4) -- functions implemented by bootloader
猜你喜欢

Solve the problem of error when typescript object gets value

西电AI专业排名超清北,南大蝉联全国第一 | 2022软科中国大学专业排名

The memory allocation of the program, the storage of local const and global const in the system memory, and the perception of pointers~

Verification code ----- SVG captcha

DSP online upgrade (2) -- design framework of bootloader

stm32mp1 Cortex M4开发篇9:扩展板空气温湿度传感器控制

Unity中的地平面简介

Stm32mp1 cortex M4 development part 13: external interrupt of expansion board key

121. Redux detailed summary + effect drawing + Case
![The most authoritative Lei niukesi in history --- embedded Ai Road line [yyds]](/img/0c/95930c7c49c5ebeee9c179c035b317.jpg)
The most authoritative Lei niukesi in history --- embedded Ai Road line [yyds]
随机推荐
ENGRAIL THERAPEUTICS公布ENX-101临床1b研究正面结果
R language sets na Rm=true parameter, deleting missing values in calculation and analysis to obtain valid calculation results (excluding missing values from analyses)
abnormal
The R language uses the sink function to export the string to the txt file in the specified directory. If no directory is specified, it will be output to the current working dir
Alibaba cloud OSS uploading and intelligent image recognition garbage recognition
Unity中的地平面简介
Optional classes, convenience functions, creating options, optional object operations, and optional streams
The most authoritative Lei niukesi in history --- embedded Ai Road line [yyds]
[practice] STM32 FreeRTOS migration series tutorial 5:freertos message queue
Clipboard learning records and pit encountered
2. the development of the meta universe
Solve the problem of error when typescript object gets value
Uni app advanced creation component / native rendering [Day9]
Mobile applications introduce static Cordova according to different platforms
Stream programming: stream support, creation, intermediate operation and terminal operation
leetcode:715. Range 模块【无脑segmentTree】
多态&Class对象&注册工厂&反射&动态代理
Are you still using localstorage directly? The thinnest in the whole network: secondary encapsulation of local storage (including encryption, decryption and expiration processing)
DSP online upgrade (4) -- functions implemented by bootloader
Celsius 的暴雷,会是加密领域的“雷曼时刻”吗?