当前位置:网站首页>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>

边栏推荐
- gin-vue-admin 使用docker容器中的数据库
- keras-ocr实例测试
- Li Hongyi 2020 deep learning and human language processing dlhlp core resolution-p21
- 事件捕获方式和冒泡方式—它们的区别是什么?
- Record of pychart running jupyter notebook in virtual environment
- Redis fast learning
- Auto encoder (AE), denoising auto encoder (DAE), variable auto encoder (VAE) differences
- Soul持续发力社交渠道赴港上市,“Soul式社交”凭什么火出圈?
- Create a container that does not depend on any underlying image
- When a subclass calls the constructor of its parent class
猜你喜欢

What if the website server is attacked? Sunflower tips that preventing loopholes is the key

Disk management and file system

Sunflower teaches you how to prevent denial of service attacks?

ES6的新特性(2)

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

PSI | CSI and ROC | AUC and KS - memorandum

To improve the baby's allergy, take yiminshu. Azg and aibeca love la Beijia work together to protect the growth of Chinese babies

Record of pychart running jupyter notebook in virtual environment

Account management and authority

Sunflower: don't worry when you encounter computer vulnerabilities, understand clearly and then judge sunflower: don't worry when you encounter computer vulnerabilities, understand clearly and then ju
随机推荐
Linux安装Redis操作
Pruning - quantification - turn to onnx Chinese series tutorials
Add virtual network card and configure OP route in win10
Converting ArcGIS style stylesheet files to GeoServer SLD files
NFS introduction and configuration
向日葵教大家如何防范拒绝服务攻击漏洞?
About the problem that Druid can't connect to the database
EasyCVR设备管理列表页面搜索时,分页数据不显示的问题修复
备忘录 @RestControllerAdvice与异常拦截类示例
FTX 基金会资助1500万帮助新冠疫苗临床实验,将影响全球公共卫生
Shell script one click configuration lamp
numpy数组和图片互转
NAT(网络地址转换)
deepsort源码解读(六)
Customer cases | focus on process experience to help bank enterprise app iteration
Express接收请求参数
A cross domain problem of golang
How can chrome quickly transfer a group of web pages (tabs) to another device (computer)
PSI|CSI和ROC|AUC和KS -备忘录
Three methods to judge whether it is palindrome structure