当前位置:网站首页>Regular expression (user name form verification / verification of landline number / regular replacement)
Regular expression (user name form verification / verification of landline number / regular replacement)
2022-07-25 23:27:00 【Dragon eyes】
1. Overview of regular expressions
1.1 What is regular expression
Regular expressions ( Regular Expression ) Is a pattern used to match character combinations in strings . stay JavaScript in , Regular expressions are also objects .
Regular tables are usually used to retrieve 、 Replace those that match a pattern ( The rules ) The text of , For example, validation forms : Only English letters can be entered in the user name form 、 Numbers or underscores , You can enter Chinese... In the nickname input box ( matching ). Besides , Regular expressions are also often used to filter out sensitive words in the content of a page ( Replace ), Or get the specific part we want from the string ( extract ) etc. .
1.2 Features of regular expressions
- flexibility 、 Very logical and functional .
- 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}$/
2. The regular expression is in js The use of
2.1 The creation of regular expressions
stay JavaScript in , Can pass There are two ways to create a regular expression .
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/;
2.2 Test regular expressions
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 false

3. Special characters in regular expressions
3.1 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/ . Special characters are also called metacharacters , In regular expressions, they are special symbols with special meanings , Such as ^ 、$ 、+ etc. .
There are many special characters , You can refer to :
jQuery manual : Regular expression part
[ Regular test tools ]( <http://tool.oschina.net/regex)
3.2 Border character
Boundary characters in regular expressions ( Position symbol ) Used to indicate the position of a character , There are mainly two characters

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
3.3 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 .
3.3.1 [] square brackets
Indicates that there are a series of characters to choose from , Just match one of them
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('!'));//true
3.3.2 Quantifier sign
Quantifier is used to set the number of times a pattern appears .

3.3.3 User name form validation
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

analysis :
- The user name can only be in English letters , Numbers , An underline or dash , And the length of the user name is 6~16 position .
- First prepare this regular expression pattern /$[a-zA-Z0-9-_]{6,16}^/
- When the form loses focus, validation begins .
- If it's a regular specification , Let's have the following span add right class .
- If it doesn't conform to the regular specification , Let's have the following span add wrong class .
<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>
3.3.4 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
Regular expression online test
3.4 Predefined classes
Predefined classes refer to shorthand for some common patterns .

Case study : Verify the landline number
var reg = /^\d{3}-\d{8}|\d{4}-\d{7}$/;
var reg = /^\d{3,4}-\d{7,8}$/;
Form validation case
// Cell phone number verification :/^1[3|4|5|7|8][0-9]{9}$/;
// Verify whether or not to change the class name of the element and the content in the element
if (reg.test(this.value)) {
// console.log(' Correct ');
this.nextElementSibling.className = 'success';
this.nextElementSibling.innerHTML = '<i class="success_icon"></i> Congratulations on entering correctly ';
} else {
// console.log(' Incorrect ');
this.nextElementSibling.className = 'error';
this.nextElementSibling.innerHTML = '<i class="error_icon"></i> Incorrect format , Please input again ';
}
//QQ Number verification : /^[1-9]\d{4,}$/;
// Nickname verification :/^[\u4e00-\u9fa5]{2,8}$/
// Verify whether or not to change the class name of the element and the content in the element , Encapsulate the matching code from the previous step , Call it many times
function regexp(ele, reg) {
ele.onblur = function() {
if (reg.test(this.value)) {
// console.log(' Correct ');
this.nextElementSibling.className = 'success';
this.nextElementSibling.innerHTML = '<i class="success_icon"></i> Congratulations on entering correctly ';
} else {
// console.log(' Incorrect ');
this.nextElementSibling.className = 'error';
this.nextElementSibling.innerHTML = '<i class="error_icon"></i> Incorrect format , Please input again ';
}
}
};
// Password authentication :/^[a-zA-Z0-9_-]{6,16}$/
// Entering the password again only needs to match the password value entered last time Is it consistent
3.5 Regular substitution replace
replace() Method can implement the replacement string operation , The argument to replace can be a string or a regular expression .
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 text = document.querySelector('textarea');
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.onclick = function() {
div.innerHTML = text.value.replace(/ fuck |gay/g, '**');
}
</script>
边栏推荐
- [wechat applet] page navigation
- 关于优先队列
- [QNX Hypervisor 2.2用户手册]9.6 gdb
- Ffmpeg first learning (only for coding)
- initializer_list工具库学习
- chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted
- Secure code warrior learning record (IV)
- TS interface
- Mongodb query and projection operators
- Why are there many snapshot tables in the BI system?
猜你喜欢

Expression of directional signal -- complex exponential signal

Grain Academy p98 trample pit e.globalexceptionhandler: null

Node基础

动态内存管理

@Import

About using NPM command under the terminal, the installation error problem is solved (my own experience)

npm+模块加载机制

Secure code warrior learning record (II)

VisualBox启动虚拟机报错:The VM session was closed before any attempt to power it on.

POI特效 市场调研
随机推荐
[QNX hypervisor 2.2 user manual]9.8 load
网格参数化Least Squares Conformal Maps实现(3D网格映射到2D平面)
ETL工具(数据同步) 二
学习探索-波浪
Why are there many snapshot tables in the BI system?
WordPress removes the website publishing time
Redis过期键的删除策略[通俗易懂]
Dynamic memory management
Thinkphp6 temporarily close the layout
[QNX hypervisor 2.2 user manual]9.7 generate
Expression of directional signal -- complex exponential signal
Serialize operator
Which securities company should a novice choose to open an account? Is it safe?
R language drawing parameters (R language plot drawing)
ratio学习之ratio_add,ratio_subtract,ratio_multiply,ratio_divide的使用
Summary of common PHP functions
How does PHP remove an element from an array based on the key value
Simulink learning notes (III) - Simulink automatic code generation (II) "suggestions collection"
推荐系统——An Embedding Learning Framework for Numerical Features in CTR Prediction
What is a physical firewall? What's the effect?