[Front-end basics] Explain regular expressions clearly - the first issue (1/5)

what is it?

A regular expression describes a pattern of string matching, which can be used to 检查determine whether a string contains a certain substring, replace a matched substring, or extract a substring that meets a certain condition from a string. string etc.
The magic of regular expressions (generally used for validation) I will illustrate intuitively with an example.

var str = '123https://blog.csdn.net/weixin_46318413123';
//如果不使用正则来选出数字(通过filter进行匹配,返回true的所有内容)
var arr = [...str].filter(e => !Number.isNaN(parseInt(e)))
console.log('未使用正则', arr.join("")); // 输出12346318413123

//如果使用正则来选出数字('\d'表示只寻找数值型,'g'表示全局寻找)
console.log('使用正则', str.match(/\d/g).join("")); // 输出12346318413123

Obviously, using regex is much more convenient than not using regex.

how to use?

This article is mainly to learn the UP main video to organize. Knowing js regular expressions, javascript front-end engineers must have skills

First, the literal creation of regular expressions

/*正则表达式字面量*/
var str = 'https://blog.csdn.net/weixin_46318413';
//创建字面量方式1
var text = '/d/g';
console.log('str是否包含d(方式1)', eval(text).test(str)) //输出为true
//创建字面量方式2
var text1 = 'd'
console.log('str是否包含d(方式2)', eval(`/${
      
      text1}/g`).test(str)) //输出为true

2. Use objects to create regular expressions

//使用对象创建正则表达式
var str = 'https://blog.csdn.net/weixin_46318413';
//使用new RegExp()创建正则表达式
var textReg = new RegExp('csdn', 'g');
console.log('str是否包含csdn(RegExp()的方式)', textReg.test(str)) //输出为true

Practical practice:
Requirements - When the user enters the content that requires a regular expression in the pop-up window (promt), the string that meets the requirements will be highlighted in red .

<!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>正则表达式-实操</title>
</head>

<body>
    <div>https://blog.csdn.net/weixin_46318413</div>
    <script>
        //首先通过dom操作获取元素
        var div = document.getElementsByTagName('div');
        //获取输入的内容
        var test = window.prompt('请输入要检测的内容,支持正则');
        // 定义正则表达式
        var reg = new RegExp(test, 'g');
        //将符合正则的字段找出来进行高亮显示
        div[0].innerHTML = div[0].innerHTML.replace(reg, search => {
      
      
            return `<span style="color:red">${ 
        search}</span>`
        })
    </script>
</body>

</html>

insert image description here
insert image description here

The use of selectors

//选择符的使用
var str = 'https://blog.csdn.net/weixin_46318413';
console.log('str是否包含cdsn或者weixin',/csdn|weixin/.test(str))//输出true

//如果匹配电话号码(只要是010或者020开头就符合要求)
var phone = '010-9999999';
console.log('号码是否有010或者020\-{7,8}',/010|020\-\d{7,8}/.test(phone)) //输出true,但是不够严谨
console.log('号码是否有010或者020\-{7,8}',/010\-\d{7,8}|020\-\d{7,8}/.test(phone)) //输出true,但是还可以缩减
console.log('号码是否有010或者020\-{7,8}',/(010|020)\-\d{7,8}/.test(phone)) //输出true(原子组,还不够严谨,可以添加限制)

4. Selectors in atom table and atom group

//[]有选择符"|"的意思,比如本题是找出是1|2|3的字符
var reg = /[123]/g;
let text = '32';
console.log(text.match(reg)) //输出['3','2']

5. Escape

//转义
let num = 22.22;
// \d表示数字 \.表示'.'(如果不加转义的话'.'表示所有都匹配)
console.log('字面量匹配',/\d+\.\d+/.test(num)) //输出true

//对象的转义与字面量就不一样了,需要多加一个'\'
var reg = new RegExp('\\d+\\.\\d+');
console.log('对象的匹配',reg.test(num)) //输出true

Hands-on Exercise:
Requirements - Using Regex to Check URLs Meet Requirements

<!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>正则表达式-实操</title>
</head>

<body>
    <script>
        //正则检查URL
        let url = 'https://www.baidu.com'
        //定义正则(字面量)
        let test = /https?:\/\/\w+\.\w+\.\w+/;
        console.log('字面量检查url', test.test(url));//输出true
        //定义regexp对象
        let reg = new RegExp('\htt\p\s?:\\/\\/\\w+\\.\\w+\\.\\w+');
        //对象的方式比较难写,可以先在console输出,如果输出的内容与字面量一样的,那就可以复制到RegExp里了
        console.log("\htt\p\s?:\\/\\/\\w+\\.\\w+\\.\\w+");//输出https?:\/\/\w+\.\w+\.\w+
        console.log('对象检查url', reg.test(url));//输出true
    </script>
</body>

</html>

6. Character boundary constraints

//字符边界约束^表示以什么开头,$表示以什么结尾
let str = '123www123';
console.log('是否以数字开头',/^\d/.test(str)) //输出true
console.log('是否以数字结尾',/\d$/.test(str)) //输出true

Practical exercise:
requirements - do a regular verification of 11-digit mobile phone number

<!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>正则表达式-实操</title>
</head>

<body>
    <input type="tel">
    <span></span>
    <script>
        /*做一个11位手机号码的验证
        
        */
        //获取input节点
        var tel = document.querySelector("[type = 'tel']");
        tel.addEventListener('keyup', function () {
      
      
            let flag = this.value.match(/^[0-9]{1,11}$/g);
            if (flag === null) {
      
      
                document.querySelector('span').innerHTML = '手机号格式有误';
            } else {
      
      
                document.querySelector('span').innerHTML = ''
            }
        })
    </script>
</body>

</html>

7. Numerical and blank metacharacters

//数值元字符\d
let str = 'csdn 2021';
//\d表示匹配数值 如果不写匹配模式,它会遇到第一个数值就会匹配结束
console.log('\d没有g', str.match(/\d/)) //输出2
//如果写了多了\d,写了几个输出几个
console.log('\d\d\d', str.match(/\d\d\d/)) //输出202
//如果写了\d+,就会输出全部的
console.log('\d+', str.match(/\d+/)) //输出2021
//如果写上匹配模式g,那就会进行全局匹配
console.log('\d有g', str.match(/\d/g)) //输出['2','0','2','1']
//\D表示匹配除了数字以外
console.log('\D', str.match(/\D/g).join("")) //输出csdn 
let msg = '    张三:010-9999999,李四:020-9999999   ';
console.log(msg.match(/\d{3}-\d{7,8}/g)) //输出['010-9999999','020-9999999']
//使用[]匹配中文([]里的都要,如果[^……]表示都不要)
console.log('[^……]', msg.match(/[^\d-:,]+/g)) //输出['    张三', '李四', '   ']
//加上\s可以去除空白
console.log('[\s]', msg.match(/[^\d-:,\s]+/g)) //输出['张三', '李四']

//空白元字符\s
console.log(/\s/.test('csdn')) //输出false,因为没有空白
console.log(/\s/.test(' csdn')) //输出true,因为有空白
console.log(/\s/.test('\ncsdn')) //输出true,因为有空白(\n换行也算空白)
console.log(/\S/.test(' \ncsdn')) //输出true,因为有字符

8. Metacharacters of w and W

//\w元字符,匹配字母、数字、下划线
//如果匹配邮箱
let email = '[email protected]';
console.log(email.match(/^\w+@\w+\.\w+$/g))  //输出['[email protected]']

//\W元字符,除了字母、数字、下划线
console.log('csdn@'.match(/\W/g)) //输出@

// 检验是否以小写字母开头的9位用户名
let username = prompt("请输入以小写字母开头的9位用户名");
console.log(/^[a-z]\w{8}$/i.test(username))

[Front-end basics] Explain regular expressions clearly - the second issue (2/5)

Since there are a lot of regular expressions, I will explain them clearly in five phases. This article has the most significant effect when combined with hands-on exercises. Regular expressions are also compulsory exam questions for many companies (large factories) , and one of my exam papers has about 5/30 questions! ! !
I will share the common problems in my usual projects and the knowledge of the written test and interview with you on CSDN, and make progress together. Come on.

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/121962879