当前位置:网站首页>regular expression
regular expression
2022-07-27 06:53:00 【THER1881】
One 、 Meaning of regular expressions
It's an object , A grammatical rule used to describe the structure of strings , The pattern used to match the character combination of characters in the string .
1、 Usage method
1、 Create a regular
1.1、 Literal measure :
let/var Variable name = / expression /
1.2、 Use RegExp Constructor for
let/var Variable name = new RegExp(/ expression /)
2、 Call relevant methods for regular pattern matching
test(): Check whether the string conforms to the regular rules
Regular objects .test()
The return value is true Indicates that it conforms to the regular rules
The return value is false Indicates that it does not conform to the regular rules
let str = '123'
let reg = /abc/ // Use literals to create regular
console.log(reg.test(str))// call test Methods to judge str Is it regular
console.log(reg1.test(reg1))
3、 Pattern modifier : Restrict regular expressions
| Modifier | explain |
|---|---|
| g | The global matching |
| i | Ignore case |
| m | Multi-line matching |
| u | With Unicode Encoding executes regular expressions |
4、 Border character
| Border character | explain |
|---|---|
| ^ | Represents the beginning text |
| $ | Text that represents the end |
let reg = /^abc$/ // Border character :
let reg1 = /^a.c$/ //. : Match except '\n' Any single character other than
let reg2 = /^a\dc$/ // \d: matching 0-9 Any number between
console.log(' first :',reg.test('abc'))
console.log(' the second :',reg.test('aac'))

You can see the regular expression created with literal , Nothing can be modified , It must be the same as regular .
5、 Predefined character :
| Predefined character | explain |
|---|---|
. | Match except ’\n’ Any single character other than |
\d | matching 0-9 Any number between |
\D | Match all 0-9 Characters other than , amount to [^0-9] |
\w | Match any letter a To z |
\W | Match division numbers , Letter , Characters other than characters , amount to [^a-zA-Z0-9] |
\s | Match spaces ( A newline 、 tabs 、 Space ) |
\S | Match characters other than spaces |
6、 Special transfer characters : With \ start
7、 Scope example :
Character class : It's a character set , Match the corresponding characters , It will find the match .

Examples of character class ranges ;

Learn more :
Character combination : If the user is allowed to input English letters ( Case insensitive )、 Numbers 、 Dash line -、 Underline _ The regular case of .
give an example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
margin:100px auto;
width: 500px;
}
.success{
color: green;
}
.wrong{
color: red;
}
</style>
<body>
<div>
user name :
<input type="text" class="uesername">
<span></span>
</div>
<script>
let reg = /^[a-zA-Z0-9_-]{6-16}$/ // Regular rules
// Get page elements
var unname = document.querySelector('.uesername')
let span = document.querySelector('span')
// to name Registration events : When name When the focus is lost, judge whether the information entered by the user conforms to the rules
unname.addEventListener('blur',function(){
let name = unname.Value
if(reg.test(name)){
span.innerHTML = ' The input format is correct '
span.className='success'
}else{
span.innerHTML = ' Input format error '
span.className = 'wrong'
}
})
</script>
</body>
</html>
Result display :


8、 Quantifier sign :
| Quantifier sign | explain |
|---|---|
? | matching ? The first character is zero or once for example hi?t |
+ | matching + One or more characters before the sign |
* | matching * Preceding characters 0 Times or times |
{n} | Match the characters before the braces n Time :hit{2}er Only match hitter |
{n,} | The characters before matching braces are the least n Time ,hit{2}er Match from hitter To hitt…er |
{n,m} | The characters before matching braces appear at least n Time , Most appear m Time |
9、 Brackets :
9.1、 You can change the scope of the qualifier
for example :catch|er // It means that it can match catch or er
ca(ch|er) // Represents a match catch or cater
9.2、 Can be grouped , When there is a quantifier after the parenthesis , It means to operate the whole group
for example :abc{2} // Indicates c Twice , Can match abcc
a(bc){2} // Indicates bc Twice , Can match abbcc
10、 Greedy matching and lazy matching
10.1、 Greedy matching : Match as many characters as possible . The default of regular matching is greedy matching
10.2、 Laziness matches : Match as few characters as possible . You can add ? Achieve lazy matching
let str = 'WBWwbw'
let reg = /w.*b/gi // Greedy matching
let reg1 = /w.*?b/gi // Inertia matching
console.log(reg.exec(str)) // Capture str
console.log(reg1.exec(str))

11、 The priority of regular expressions :
\( Escape character ) The highest priority
()、[]、 qualifiers --> Secondary priority
Locator (^,$) ---> Three priority
|( Or operator ) ----> Last
practice : The page contains email, Define regular expressions , Verify the input email Is it legal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="text-align: center;">
mailbox :<input type="text" id="email">
<span></span>
<script>
let email = document.querySelector('#email')
let span = document.querySelector('span')
email.addEventListener('blur',function(){
let reg= /^([0-9A-Za-z]+)@([0-9a-z]+.[a-z]{2,3}(.[a-z]{2})?)$/g;
// Get email
let num = this.value.trim()
if(reg.test(num)){
span.innerHTML = ' Input correct '
}else{
span.innerHTML = ' Input error '
}
})
</script>
</body>
</html>

边栏推荐
- How can chrome quickly transfer a group of web pages (tabs) to another device (computer)
- FTX.US推出股票和ETF交易服务,让交易更透明
- How to delete or replace the loading style of easyplayer streaming media player?
- 银行业客户体验管理现状与优化策略分析
- Install redis under Windows
- Project training experience 2
- Introduction to the official functions of easyrecovery14 data recovery software
- Some applications of std:: bind and std:: function
- FTX US launched FTX stocks, striding forward to the mainstream financial industry
- Log in to Alibaba cloud server with a key
猜你喜欢

What is the reason why the channel list is empty on the intelligent security video platform easycvr?

如何删除或替换EasyPlayer流媒体播放器的loading样式?

Many of the world's top 500 enterprises gathered at the second digital Expo, and the digital industry curtain is about to open!

Introduction to the official functions of easyrecovery14 data recovery software

Detection and identification data set and yolov5 model of helmet reflective clothing

How to avoid loopholes? Sunflower remote explains the safe use methods in different scenarios

【11】 Binary code: "holding two roller handcuffs, crying out for hot hot hot"?

关于ES6的新特性

Publish a building segmentation database with a resolution of 0.22m

向日葵全面科普,为你的远程控制设备及时规避漏洞
随机推荐
2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!
MangoDB
Raid explanation and configuration
Shell script one click configuration lamp
ES6 new features (getting started)
账号管理与权限
Memo @restcontrolleradvice and exception interception class example
Rsync remote synchronization
改善宝宝过敏就吃伊敏舒,azg与Aibeca爱楽倍佳携手守护中国宝宝成长
Tips - completely delete the files on the USB flash drive
Go语言学习
Is it feasible to fix the vulnerability with one click? Sunflower to tell you that one click fix vulnerability is feasible? Sunflower to tell you that one click fix vulnerability is feasible? Sunflowe
deepsort源码解读(四)
Three methods to judge whether it is palindrome structure
px4源码编译之 建立自己的程序模块
Redis fast learning
正则表达式
Code random notes_ Hash_ 242 effective letter heterotopic words
Record of pychart running jupyter notebook in virtual environment
Speech and language processing (3rd ed. draft) Chapter 2 - regular expression, text normalization, editing distance reading notes