Home > Web Front-end > JS Tutorial > body text

JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis

php是最好的语言
Release: 2018-08-08 14:23:25
Original
2329 people have browsed it

How to use JS regular expressions? To use regular expressions in JavaScript, you must first create a regular expression object: literal writing - starting and ending with a slash; built-in constructor generation - getting the object through instantiation. Regular expressions actually describe a string matching pattern, which can be used to check whether a string contains a certain substring, replace the matching substring, or extract a substring that meets a certain condition from a string. Every computer programming language supports regular expressions. This article will describe regular expressions in detail.

Chapter 1 What is a regular expression

1.1 Overview

<body>    <img src="JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis" alt=""></body><script>    var img = document.querySelector(&#39;img&#39;);    img.onclick = function(){        if(this.src.indexOf("JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis")>0){            this.src="2.jpg";        }else{            this.src="JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis";        }    }</script>
Copy after login

In the above code, the indexOf() method of the sting object in the standard library is used during judgment; it is used to determine the position of a string in another string and returns an integer indicating the starting position of the match. If -1 is returned, it means there is no match;

##It can be seen that the function of indexOf is to find the string; in real project development, the string Search operations are very common;

For example, determine whether there are numbers and letters in the password, whether the mobile phone number is 11 and digits, etc... To complete these complex search operations, We need to use another tool, this is what we want to learnregular expression;

Regular expression (regular expression) describes a string matching method Pattern can be used to check whether a string contains a certain substring, replace the matching substring, or extract a substring that meets a certain condition from a string, etc.

Every computer programming language supports regular expressions

What can regular expressions help us do?

Data hiding (188520 Mr. Li) Data collection (data crawler) Data filtering (Forum sensitive word filtering) Data verification (form Verification, mobile phone number, email address...)

1.2 Getting Started

Verify whether there is the number 8 in a string;

var t = &#39;sda43645dfgkl&#39;;//定义一个正则var reg = /8/;//判断字符串是否符合表达式的定义alert(reg.test(t)); //false
Copy after login

In the above code, there is no number 8 in the string, so the detection result is flase;

var t = &#39;sda43645dfgkl&#39;;//定义一个正则var reg = /\d/;//判断字符串是否符合表达式的定义alert(reg.test(t)); //true
Copy after login

\d is a character cluster, indicating 0 The number of -9; I will explain what a character cluster is later

第2章 在JavaScript中使用正则

2.1 创建正则对象

1:字面量写法-以斜杠表示开始和结束; var regex = /xyz/;2:内置构造函数生成-通过实例化得到对象;var regex = new RegExp(&#39;xyz&#39;);

上面两种写法是等价的,都新建了一个内容为 xyz 的正则表达式对象。

var t = &#39;sda43645dfgkl&#39;;var reg = /\d/; //字面量var reg = new RegExp(&#39;\d&#39;); //构造函数console.log(reg.test(t));
Copy after login

考虑到书写的便利和直观,实际应用中,基本上都采用字面量的写法。

2.2 正则对象的方法

test(str) :判断字符串中是否具有指定模式的子串,返回结果是一个布尔类型的值;exec(str) :返回字符串中指定模式的子串,一次只能获取一个与之匹配的结果;

<body>    <input type="text" id="inp">    <input type="button" id="btu" value="匹配"></body><script>    var btu = document.querySelector(&#39;#btu&#39;);    btu.onclick = function(){        var t = document.querySelector(&#39;#inp&#39;).value;        var reg = /\d\d\d/;        console.log(reg.test(t));//返回是否匹配成功的布尔值        console.log(reg.exec(t));//返回匹配后的结果,匹配失败返回null    }</script>
Copy after login

2.3 String对象的方法

search(reg) :与indexOf非常类似,返回指定模式的子串在字符串首次出现的位置match(reg) :以数组的形式返回指定模式的字符串,可以返回所有匹配的结果replace(reg,'替换后的字符') :把指定模式的子串进行替换操作split(reg) :以指定模式分割字符串,返回结果为数组

<body>    <input type="text" id="inp">    <input type="button" id="btu" value="匹配"></body><script>    var btu = document.querySelector(&#39;#btu&#39;);    btu.onclick = function(){        var t = document.querySelector(&#39;#inp&#39;).value;        var reg = /\d\d\d/;        //返回第一次出现符合的字符串的位置        console.log(t.search(reg));        //数组形式返回符合规则的字符串,使用g则返回全部匹配结果        console.log(t.match(reg));        //替换符合规则的字符串,使用g则全部替换        console.log(t.replace(reg,&#39;***&#39;));        //以规则为分割标志,分割整个字符串,以数组形式返回分割结果        console.log(t.split(reg));    }</script>
Copy after login

第3章 几个重要的概念

子表达式在正则表达式中,通过一对圆括号括起来的内容,我们就称之为“子表达式”。如:var reg = /\d(\d)\d/gi;

捕获在正则表达式中,子表达式匹配到相应的内容时,系统会自动捕获这个行为,然后将子表达式匹配到的内容放入系统的缓存区中。我们把这个过程就称之为“捕获”。

JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis反向引用

在正则表达式中,我们可以使用\n(n>0,正整数,代表系统中的缓冲区编号)来获取缓冲区中的内容,我们把这个过程就称之为“反向引用”。

JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis这些比较重要的概念,在什么情况下可能被用到?

例:查找连续的相同的四个数字,如:1111、6666

var str = &#39;gh2396666j98889&#39;;// 1:子表达式匹配数组// 2:发生捕获行为,把子表达式匹配的结果放入缓存区// 3:使用反向引用获取缓存中的结果进行匹配var reg = /(\d)\1\1\1/;console.log(str.match(reg));
Copy after login

练习

例1:查找连续的四个数字,如:3569

答:var reg = /\d\d\d\d/gi;

例2:查找数字,如:1221,3443答:var reg = /(\d)(\d)\2\1/gi;

Example 3: Find characters, such as: AABB, TTMM (Tip: In regular expressions, use [A-Z] to match any character in A-Z) Answer: var reg = /([A-Z ])\1( [A-Z])\2/g;

Example 4: Find the same four consecutive numbers or four characters (Tip: In the regular expression in, through [0-9a-z])Answer: var reg = /([0-9a-z])\1\1\1/gi;

Chapter 4 Writing Regular Expressions

##4.1 Regular expression composition

Regular expressions are composed of ordinary characters (such as the character a to z) and special characters (called metacharacters). A regular expression acts as a template that matches a character pattern with a searched string.

Three steps of regular expression ① Matching character (what to search) ② Qualifier (how much to search) ③ Locator (where to search)

4.2 Matching character (what to search for)

Matching character: Character matching character is used to match one or certain characters; the \d used earlier is matching A number 0-9

In a regular expression, the content enclosed by a pair of square brackets is called a "character cluster". Character cluster represents a range, but when matching, it can only match fixed results in a certain range.

Character clusterMeaning
[a-z] Matches any character between character a and character z
[ A-Z] Matches any character between character A and character Z
[0-9]Match any number between 0 and 9
[0-9a-z] Matches any character from 0 to 9 or from character a to character z
[0-9a-zA -Z] Matches any character from 0 to 9 or from character a to character z or from character A to character Z
[abcd] Matches character a or character b or character c or character d
[1234]matches number 1 or number 2 or number 3 or number 4

In the character cluster, a ^ (caret) is used to express the meaning of negation.

Character clusterMeaning
[^a-z] Matches any character except characters a to z
[^0-9] Matches any character except the numbers 0 to 9
[^abcd]Match any character except a, b, c, d

Metacharacters (commonly used)

var str = &#39;gh23.9h西688岭8老4湿9&#39;;var reg = /\w/;//匹配数字字母下划线console.log(str.match(reg));var reg = /[4-8]/;//匹配4-8的数字console.log(str.match(reg));var reg = /./;//匹配除 "\n" 之外的任何单个字符console.log(str.match(reg));var reg = /./;//匹配除 "\n" 之外的任何单个字符console.log(str.match(reg));var reg = /[\u4e00-\u9fa5]/; //匹配中文字符中的任一字符console.log(str.match(reg));
Copy after login

4.3 限定符(查多少)

什么是限定符?限定符可以指定正则表达式的一个给定字符必须要出现多少次才能满足匹配。

* :匹配前面的子表达式零次或多次,0到多+ :匹配前面的子表达式一次或多次,1到多? :匹配前面的子表达式零次或一次,0或1{n} :匹配确定的 n 次 {n,} :至少匹配 n 次 {n,m} :最少匹配 n 次且最多匹配 m 次
Copy after login

对QQ号码进行校验要求5~11位,不能以0开头,只能是数字

var str = &#39;我的QQ20869921366666666666,nsd你的是6726832618吗?&#39;;var reg = /[1-9]\d{4,10}/g;console.log(str.match(reg));
Copy after login

JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis我们会发现以上代码运行结果中,默认优先配到 13 位,在对后面的进行匹配;

为什么不是优先匹配 5 位后,在对后面的进行匹配呢?

因为在正则表达式中,默认情况下,能匹配多的就不匹配少的,我们把这种匹配模式就称之为 贪婪匹配,也叫做 贪婪模式所有的正则表达式,默认情况下采用的都是贪婪匹配原则。

如果在限定符的后面添加一个问号?,那我们的贪婪匹配原则就会转化为非贪婪匹配原则,优先匹配少的,也叫惰性匹配;

var str = &#39;我的QQ20869921366666666666,nsd你的是6726832618吗?&#39;;//非贪婪模式匹配,var reg = /[1-9]\d{4,12}?/g;console.log(str.match(reg));
Copy after login

JS Tutorial: What is a regular expression? JS regular expression verification syntax analysisJS Tutorial: What is a regular expression? JS regular expression verification syntax analysis

4.4 定位符(从哪查)

编写正则表达式,匹配手机号码?(注册功能)纯数字第一位必须是1开头第二位必须是3、4、5、7、8第三位~第十一只要是数字即可

var str = &#39;lsd15309873475&#39;;var reg = /1[34578]\d{9}/;    console.log(reg.test(str));//结果true
Copy after login

检测结果为真,但是,字符串并不是一个手机号;正则表达式只会到字符串去寻找是否有与之匹配的结果,如果有,就认为是正确的,而不考虑其字符串本身是否合法。如何解决以上问题呢?

定位符可以将一个正则表达式固定在一行的开始或结束。也可以创建只在单词内或只在单词的开始或结尾处出现的正则表达式。

^ (脱字符):匹配输入字符串的开始位置$ :匹配输入字符串的结束位置\b :匹配一个单词边界\B :匹配非单词边界
Copy after login

注意: ^ 放在字符簇中是取反的意思,放在整个表达式中是开始位置;

var str = &#39;lsd15309873475&#39;;var reg = /^1[34578]\d{9}$/;    console.log(reg.test(str));//false
Copy after login
 var str = &#39;i am zhangsan&#39;;//an必须是一个完整的单词var reg = /\ban\b/;console.log(str.match(reg));//an不能是单词的开始,只能是单词的结束var reg = /\Ban\b/;console.log(str.match(reg));
Copy after login

4.5 匹配模式 & 修饰符

匹配模式也就修饰符:表示正则匹配的附加规则,放在正则模式的最尾部。修饰符可以单个使用,也可以多个一起使用。

在正则表达式中,匹配模式常用的有两种形式:g :global缩写,代表全局匹配,匹配出所有满足条件的结果,不加g第一次匹配成功后,正则对象就停止向下匹配;i :ignore缩写,代表忽略大小写,匹配时,会自动忽略字符串的大小写

语法:var reg = /正则表达式/匹配模式;

var t = &#39;sda43645dfgkl&#39;;var reg = /Da/; //匹配结果为falsevar reg = /Da/i; //匹配结果为tureconsole.log(reg.test(t));
Copy after login

4.6 转义字符

因为在正则表达式中 .(点) + \ 等是属于表达式的一部分,但是我们在匹配时,字符串中也需要匹配这些特殊字符,所以,我们必须使用 *反斜杠* 对某些特殊字符进行转义;需要转义的字符:

点号.小括号()中括号[]左斜杠/右斜杠\选择匹配符|* ?{}+ $^
Copy after login

匹配一个合法的网址URL:

var str = &#39;http://xiling.me&#39;;// 对于 . / 都必须转义匹配 var reg = /\w+:\/\/\w+\.\w+/;console.log(str.match(reg));
Copy after login

使用正则表达式验证邮箱是否合法

var str = &#39;qq@qq.com&#39;;var reg = /\w+@[0-9a-z]+(\.[0-9a-z]{2,6})+/;console.log(str.match(reg));
Copy after login

4.7 或者的用法

查找所有属于苹果旗下的产品

var str = &#39;ipad,iphone,imac,ipod,iamsorry&#39;;var reg = /\bi(pad|phone|mac|pod)\b/g;console.log(str.match(reg));
Copy after login

相关推荐:

正则表达式的JS验证

浅谈正则表达式,正则表达式

The above is the detailed content of JS Tutorial: What is a regular expression? JS regular expression verification syntax analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Character clusterMeaning
\d Matches a numeric character, equivalent to using [0-9]
\D matches a non-numeric character, you can also use [^0-9]
\w Matches any alphanumeric underscore character including the underscore, you can also use [0-9a-zA-Z_]
\W Matches any non-alphanumeric underscore character, you can also use [^\w]
\s Matches any whitespace character
\S## matches any non-whitespace character, you can also use [^\s]
. Matches any single character except "\n" (newline)
[\u4e00-\u9fa5] Matches Chinese characters