当前位置:网站首页>regular expression
regular expression
2022-07-28 02:21:00 【Taro paste】
summary
What is regular expression
Regular expressions ( Regular Expression ) Is a pattern used to match character combinations in strings . stay JavaScript in , Regular expressions, too object .
effect
- validate form : Only English letters can be entered in the user name form 、 Numbers or underscores , You can enter Chinese... In the nickname input box ( matching )
- It is also often used to filter out some sensitive words in the page content ( Replace )
- Get the specific part we want from the string ( extract )
Features of regular expressions
flexibility 、 Logicality and Functionality Very strong .
Complex control of strings can be achieved quickly and in a very simple way .
For new contacts , It's more obscure . such as :^\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$
The actual development , Generally, regular expressions are copied directly . However, it is required to use regular expressions and modify them according to the actual situation . For example, user name : /^[a-z0-9_-]{3,16}$/
The use of regular expressions
The creation of regular expressions
stay JavaScript in , You can create a regular expression in two ways .
Mode one : By calling RegExp Object's constructor creation
var regexp = new RegExp(/123/);
console.log(regexp);Mode two : Use literal to create Regular expressions
var rg = /123/;Test regular expressions (test())
test() Regular object methods , Used to detect whether a string conforms to this rule , The object will return true or false, Its parameter is the test string .
var rg = /123/;
console.log(rg.test(123));// Whether... Appears in the matching character 123 The result is true
console.log(rg.test('abc'));// Whether... Appears in the matching character 123 No, the result is falseSpecial characters in regular expressions
The composition of regular expressions
A regular expression can be made up of simple characters , such as /abc/, It can also be a combination of simple and special characters , such as /ab*c/ . among Special characters Also known as Metacharacters , In regular expressions, they are special symbols with special meanings , Such as ^ 、$ 、+ etc. .
There are many special characters , For details, please refer to MDN
Border character
Boundary characters in regular expressions ( Position symbol ) Used to indicate the position of a character , There are mainly two characters
| Border character | explain |
|---|---|
| ^ | Text that matches the beginning of a line ( Start with who ) |
| $ | Text that matches the end of a line ( By whom ) |
- If ^ and $ together , The representation must be an exact match
var rg = /abc/; // There's no need for quotation marks in regular expressions Whether numeric or string
// /abc/ As long as it contains abc This string returns true
console.log(rg.test('abc'));
console.log(rg.test('abcd'));
console.log(rg.test('aabcd'));
console.log('---------------------------');
var reg = /^abc/;
console.log(reg.test('abc')); // true
console.log(reg.test('abcd')); // true
console.log(reg.test('aabcd')); // false
console.log('---------------------------');
var reg1 = /^abc$/; // Exactly match The requirement must be abc Only strings conform to the specification
console.log(reg1.test('abc')); // true
console.log(reg1.test('abcd')); // false
console.log(reg1.test('aabcd')); // false
console.log(reg1.test('abcabc')); // false
Character class
Character class means that there are a series of characters to choose from , Just match one of them . All available characters are enclosed in square brackets .
[] square brackets
Indicates that there are a series of characters to choose from , Just match one of them One That's all right. ( A commonplace )
var rg = /[abc]/; // As long as it contains a perhaps contains b Or contain c All return as true
console.log(rg.test('andy'));//true
console.log(rg.test('baby'));//true
console.log(rg.test('color'));//true
console.log(rg.test('red'));//false
var rg1 = /^[abc]$/; // Choose one of three Only yes a Or is it b Or is it c These three letters return to true
console.log(rg1.test('aa'));//false
console.log(rg1.test('a'));//true
console.log(rg1.test('b'));//true
console.log(rg1.test('c'));//true
console.log(rg1.test('abc'));//true
----------------------------------------------------------------------------------
var reg = /^[a-z]$/ //26 English letters, any letter returns true - It means a To z The scope of the
console.log(reg.test('a'));//true
console.log(reg.test('z'));//true
console.log(reg.test('A'));//false
-----------------------------------------------------------------------------------
// Character combination
var reg1 = /^[a-zA-Z0-9]$/; // 26 English letters ( Both uppercase and lowercase ) Any letter returns true
------------------------------------------------------------------------------------
// Take the opposite Add inside square brackets ^ Representation inversion , Just include the characters in square brackets , All back to false .
var reg2 = /^[^a-zA-Z0-9]$/;
console.log(reg2.test('a'));//false
console.log(reg2.test('B'));//false
console.log(reg2.test(8));//false
console.log(reg2.test('!'));//trueQuantifier sign
Quantifier is used to set the occurrence of a certain pattern frequency .
| quantifiers | explain |
|---|---|
| * | repeat 0 Times or more |
| + | repeat 1 Times or more |
| ? | repeat 0 Time or 1 Time |
| {n} | repeat n Time |
| {n,} | repeat n Times or more |
| {n,m} | repeat n To m Time |
User name form verification case
functional requirement :
If the user name is legal , Then the following prompt message is : The user name is legal , And the color is green
If the user name is not legal , Then the following prompt message is : The user name does not conform to the specification , And the color is red

<input type="text" class="uname"> <span> Please enter a user name </span>
<script>
// Quantifier is to set the number of times a pattern appears
var reg = /^[a-zA-Z0-9_-]{6,16}$/; // In this mode, users can only input English letters Numbers Underline Center line
var uname = document.querySelector('.uname');
var span = document.querySelector('span');
uname.onblur = function() {
if (reg.test(this.value)) {
console.log(' Correct ');
span.className = 'right';
span.innerHTML = ' The user name format is correct ';
} else {
console.log(' FALSE ');
span.className = 'wrong';
span.innerHTML = ' Incorrect user name format ';
}
}
</script>
Brackets summarize
1. Curly braces Quantifier sign . It means the number of repetitions
2. brackets Character set . Match any character in the formula bracket .
3. Parentheses indicate priority
Predefined classes
Predefined classes refer to shorthand for some common patterns .
| Scheduled class | explain |
|---|---|
| \d | matching 0-9 Any number between , amount to [0-9] |
| \D | matching 0-9 Any character other than , amount to [^0-9] |
| \w | Match any letter , Numbers , Underline , amount to [A-Za-z0-9_] |
| \W | Match any letter , Numbers , Characters other than underscores , amount to [^A-Za-z0-9_] |
| \s | Match spaces ( Include line breaks , tabs , Spaces, etc ), amount to [\t\r\n\v\f] |
| \S | Match characters that are not spaces , amount to [^\t\r\n\v\f] |
Form validation case
window.addEventListener('load', function () {
// Cell phone number verification
var tel = document.querySelector('#tel');
var telreg = /^1[3|4|5|7|8|][\d]{9}$/;
reg(tel, telreg);
//qq Number verification
var qq = this.document.querySelector("#qq");
var qqreg = /^[1-9]\d{4,}$/;
reg(qq, qqreg);
//qq Nickname verification
var nc = this.document.querySelector('#nc');
var ncreg = /^[\u4e00-\u9fa5]{2,8}$/;
reg(nc, ncreg);
// SMS verification
var msg = this.document.querySelector('#msg');
var msgreg = /^[\d]{6}$/;
reg(msg, msgreg);
// Password authentication
var psw = this.document.querySelector('#psw');
var pswreg = /^[0-9A-Za-z_-]{6,16}$/
reg(psw, pswreg);
function reg(ele, reg) {
ele.addEventListener('blur', function () {
if (reg.test(this.value)) {
this.nextElementSibling.innerHTML = ' The input format is correct ';
this.nextElementSibling.className = 'right';
} else {
this.nextElementSibling.innerHTML = ' Incorrect format , Please re-enter ';
this.nextElementSibling.className = 'error';
}
})
}
// Verify that the two passwords are consistent
var surepsw = this.document.querySelector('#surepsw');
surepsw.addEventListener('blur', function () {
if (surepsw.value == psw.value) {
this.nextElementSibling.innerHTML = ' The password is correct ';
this.nextElementSibling.className = 'right';
} else {
this.nextElementSibling.innerHTML = ' The two passwords don't match , Please re-enter ';
this.nextElementSibling.className = 'error';
}
})
})Regular substitution replace
replace() Method can implement the replacement string operation , The argument to replace can be a string or a regular expression .
Regular expression parameters
/ expression /[ Parameters ]
- g: The global matching
- i: Ignore case
- gi: The global matching + Ignore case
var str = 'andy and red';
var newStr = str.replace('andy', 'baby');
console.log(newStr)//baby and red
// Equate to Here andy Can be written in regular expressions
var newStr2 = str.replace(/andy/, 'baby');
console.log(newStr2)//baby and red
// All replacement
var str = 'abcabc'
var nStr = str.replace(/a/,' ha-ha ')
console.log(nStr) // ha-ha bcabc
// All replacement g
var nStr = str.replace(/a/a,' ha-ha ')
console.log(nStr) // ha-ha bc ha-ha bc
// Ignore case i
var str = 'aAbcAba';
var newStr = str.replace(/a/gi,' ha-ha ')//" Ha ha ha ha bc ha-ha b ha-ha "Case study : Filter sensitive words
<textarea name="" id="message"></textarea> <button> Submit </button>
<div></div>
<script>
var message = document.querySelector('#message');
var btn = document.querySelector('button');
var text = document.querySelector('div');
btn.addEventListener('click', function () {
text.innerHTML = message.value.replace(/ passion /g, '**');
})
</script>边栏推荐
- 视频常用分辨率
- The principle and implementation of loss function cross entropy
- 借助Elephant&nbsp;Swap打造的ePLATO,背后的高溢价解析
- MySQL pymysql operation
- 智能合约安全——selfdestruct攻击
- 【网站搭建】使用acme.sh更新ssl证书:将zerossl改为letsencrypt
- MySQL的pymysql操作
- 损失函数-交叉熵的原理及实现
- 一文读懂Plato&nbsp;Farm的ePLATO,以及其高溢价缘由
- 对话Atlassian认证专家叶燕秀:Atlassian产品进入后Server时代,中国用户应当何去何从?
猜你喜欢

探究flex-basis

Leetcode hot topic Hot 100 - > 1. Sum of two numbers

Flex layout learning completed on PC side

SkyWalking分布式系统应用程序性能监控工具-中

Go learn 02 basic knowledge

Day6 函数和模块的使用

Huawei app UI automation test post interview real questions, real interview experience.

Appium 点击操作梳理

Two ways for wechat applet to realize dynamic horizontal step bar

The cooperation between starfish OS and metabell is just the beginning
随机推荐
轻量版项目管理系统
你所不知道的WMS
Promise from introduction to mastery (Chapter 1 Introduction and basic use of promise)
uniapp 总结篇 (小程序)
Promise从入门到精通 (第2章 Promise的理解和使用)
软工必备知识点
The level "trap" of test / development programmers is not a measure of one-dimensional ability
Promise from introduction to mastery (Chapter 2 understanding and use of promise)
54:第五章:开发admin管理服务:7:人脸入库流程;人脸登录流程;浏览器开启视频调试模式(以便能够在本机的不安全域名的情况下,也能去开启摄像头);
Flume(5个demo轻松入门)
Xiaomi website homepage big module - small module + navigation (floating case)
How to put app on the app store?
Sample imbalance - entry 0
Ceresdao: new endorsement of ventures Dao
Uniapp summary (applet)
Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
Leetcode hot topic Hot 100 - > 2. Add two numbers
每条你收藏的资讯背后,都离不开TA
测试/开发程序员的级别“陷阱“,级别不是衡量单维度的能力......
feign调用get和post记录