当前位置:网站首页>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>边栏推荐
- Software testing interview question: what is the purpose of test planning? What are the contents of the test plan? Which are the most important?
- 这个操作可能不值钱,但却值得学习 | 【图片批量裁剪】
- Promise from introduction to mastery (Chapter 4 async and await)
- MPLS tunnel experiment
- Promise from getting started to mastering (Chapter 3: customize (handwriting) promise)
- feign调用get和post记录
- 考研数学一元微分学证明题常见题型方法
- LeetCode 热题 HOT 100 -> 2.两数相加
- Promise from introduction to mastery (Chapter 2 understanding and use of promise)
- CeresDAO:全球首个基于DAO赋能Web3.0的去中心化数字资产管理协议
猜你喜欢

APP如何上架App Store?

A lock faster than read-write lock. Don't get to know it quickly

Codeworks round 810 (Div. 2) a~c problem solution

LeetCode 热题 HOT 100 -> 2.两数相加

执行 Add-Migration 迁移时报 Build failed.

Promise从入门到精通 (第2章 Promise的理解和使用)

Aike AI frontier promotion (7.14)

样本不均衡-入门0

Flex development web page instance web side

小程序毕设作品之微信校园维修报修小程序毕业设计成品(4)开题报告
随机推荐
Skywalking distributed system application performance monitoring tool - medium
【网站搭建】使用acme.sh更新ssl证书:将zerossl改为letsencrypt
Xiaomi website homepage big module - small module + navigation (floating case)
获取两个集合相差数据
正则表达式
The cooperation between starfish OS and metabell is just the beginning
Promise从入门到精通(第4章 async 和 await)
The level "trap" of test / development programmers is not a measure of one-dimensional ability
Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
In it, there is a million talent gap, and the salary rises, but it is not capped
Ceresdao: new endorsement of ventures Dao
【数据库数据恢复】SQL Server数据库磁盘空间不足的数据恢复案例
如何评估研发人员效能?软件工程师报告帮你看见每个人的贡献
Leetcode hot topic Hot 100 - > 3. longest substring without repeated characters
Promise从入门到精通(第3章 自定义(手写)Promise)
Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further
LeetCode 热题 HOT 100 -> 3. 无重复字符的最长子串
Appium click operation sorting
Common video resolution
Promise从入门到精通 (第1章 Promise的介绍和基本使用)