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

Detailed explanation of the use of the most basic regular expressions in JS

php中世界最好的语言
Release: 2018-03-30 14:15:21
Original
1559 people have browsed it

This time I will bring you the most basic regular expressions in JSDetailed explanation of usage, what are the precautionsfor using basic regular expressions in JS, the following are practical cases , let’s take a look.

Regular expressions are a very powerful thing. Today I will just briefly introduce them to those who are new to JS. If there are any controversial aspects, please leave a message!

1.1 What is a regular expression

A regular expression is an object that describes a character pattern. ECMAScript The RegExp class represents regular expressions, and both String and RegExp define functions for powerful pattern matching and text retrieval and replacement using regular expressions.

Regular expressions are used to match string patterns and retrieve and replace them. They are a powerful tool for performing pattern matching on strings.

1.2 The role of regular expressions

Regular expressions are mainly used to verify the input data of the client.

After the user fills out the form and clicks the button, the form will be sent to the server. On the server side, server scripts such as PHP, ASP.NET, and JSP are usually used for further processing. Because of client-side verification, it can save a lot of server-side system resources and provide a better user experience.

2. Create a regular expression==(123)==

To use a regular expression, you must first create a regular expression Expression object , there are 2 ways to create an object :

2.1 Method 1: Use the keyword new to create

var patt = new RegExp(pattern,modifiers);
Copy after login

parameters 1: Regular expression pattern. String form

Parameter 2: Mode modifier. Used to specify global matching, case-sensitive matching and multi-line matching

<script type="text/javascript">
  /*
   创建了一个正则表达式
   参数1:模式是:girl,意思是说可以匹配 "girl"这样的字符串
   参数2:模式修饰符:gi g代表全局匹配 i代表不区分大小写
  */
 var pa = new RegExp("girl", "gi");
  //测试参数中的字符串"你好我的girl" 是否与匹配模式匹配。
  var isExist = pa.test("你好我的girl"); // 在本例中,是匹配的,这个字符串包含girl,所以返回true
  alert(isExist); //true
</script>
Copy after login

2.2 Method 2: Use regular expressions to directly quantify

var pa = /pattern/modifiers;
Copy after login

Two/middle ones Represents the pattern of a regular expression. The last / is followed by the pattern modifier

. For example: the above example can be written like this: var pa = /girl/gi;

Note: At this time, the pattern and Pattern modifiers can be added with double quotes or single quotes

<script type="text/javascript">
 var pa = /girl/gi;
 alert(pa.test("厉害了我的girl")); //true
</script>
Copy after login

3. Regular expression pattern modifiers==(126)==

There are three mode modifiers in JavaScript: g i u

  1. g: indicates global. This means that a string will be matched multiple times. If g is not written, it will only be matched once. Once the match is successful, it will not be matched again.

  2. i: Indicates that case is ignored. This means that the matching is not case-sensitive.

  3. u: Indicates that multiple lines can be matched.

4. Detailed explanation of regular expression methods==(127)==

Frequently used regular expressions There are two test() and exec() methods

4.1 test() method

test(string)

  • Parameter: The string to be matched

  • Return value: Return true if the match is successful, false if failed

If you only want to know the target character This method is very convenient when you don't need to know whether a string matches a certain pattern, but you don't need to know its text content. Therefore, the test() method is often used in if statements.

<script type="text/javascript">
 var pa = /girl/gi;
 if(pa.test("厉害了我的girl")){
  alert("这个女孩和你很配");
 }else {
  alert("你注定没有女孩去匹配");
 }
</script>
Copy after login

4.2 exec() method

exec(string): This method is specially designed for capturing groups

  • Parameter: The string to be matched

  • Return value: An array is returned. If there is no match, return null

  • Explanation about the return value array:

  • It is indeed an instance of Array.

  • But this array has two additional attributes: index and input

  • index: indicates where the matched string is in the source string Index

  • #input: Indicates the matched source string.

  • 数组的第一项目是与整个模式匹配的字符串,其他项是与模式中捕获组匹配的字符串

  • 如果没有捕获组,则数组中只有第一项。关于捕获组的概念以后再说

<script type="text/javascript">
 var pa = /girl/gi;
 var testStr = "myGirl, yourgirl, hisgIrl";
 var girls = pa.exec(testStr); //捕获
 alert(girls.length + ":" + (girls instanceof Array)); //正则表达式没有捕获组,所以数组长度为1
 alert(girls[0]); //第一次捕获的是 Girl
  //因为我们是用的全局匹配,所以此次匹配的时候从上次匹后的位置开始继续匹配
 alert(pa.exec(testStr)[0]);  // girl
 alert(pa.exec(testStr)); // gIrl
 alert(pa.exec(testStr)); //继续向后没有匹配的字符串,所以返回null
  // 返回null,如果继续再匹配,则会回到字符串的开始,重写开始匹配。
 alert(pa.exec(testStr)); // Girl
  // ...开启新一轮匹配
</script>
Copy after login

所以我们如果想找到全部匹配的字符串可以时候用循环,结束条件就是匹配结果为null

<script type="text/javascript">
 var pa = /girl/gi;
 var testStr = "myGirl, yourgirl, hisgIrl";
 var girls;
 while(girls = pa.exec(testStr)){ //如果等于null,会自动转成 false,结束。
  alert(girls);
 }
</script>
Copy after login

分组。在正则表达式中用()括起来任务是一组。组可以嵌套。

<script type="text/javascript">
  //()内的内容就是第1组(Girl),其实我们完整真个表达式可以看出第0组 girl(Girl)
  // 将来对应着匹配结果数组的下标。 
 var pa = /girl(Girl)/gi; 
 var test = "girlGirl abdfjla Girlgirl fal girl";
 var girls;
 while(girls = pa.exec(test)){
  //匹配之后,数组的第0个元素对应的这第0组的匹配结果,第1个元素对应着第1组的匹配结果
  for (var i = 0; i < girls.length; i++) {
   console.log(girls[i]);
  }
  console.log("-------------");
 }
</script>
//最终运行结果:
girlGirl
Girl
-------------
Girlgirl
girl
------------
Copy after login

五、正则表达式规则==(124)==

表达式规则

正则表达式元字符是包含特殊含义的字符。它们有一些特殊功能,可以控制匹配模式的

方式。反斜杠后的元字符将失去其特殊含义。

字符类:单个字符和数字

[0-9A-Za-z] 
元字符/元符号                    匹配情况
.                         匹配除换行符外的任意字符
[a-z0-9]                     匹配括号中的字符集中的任意字符
[^a-z0-9]                     匹配任意不在括号中的字符集中的字符
\d ==[0-9]                    匹配数字
\D ==[^0-9]                        匹配非数字,同[^0-9]相同
\w     [0-9A-Za-z_]                    匹配字母和数字及_
\W                         匹配非(字母和数字及_)

字符类:空白字符
元字符/元符号                    匹配情况
\0                             匹配null 字符
\b                             匹配空格字符
\n                             匹配换行符
\r                             匹配回车字符
\t                             匹配制表符
\s                             匹配空白字符、空格、制表符和换行符
\S                             匹配非空白字符

字符类:锚字符

元字符/元符号                    匹配情况
^                             行首匹配
$                             行尾匹配

字符类:重复字符
元字符/元符号                                匹配情况
?  例如(x?)                            匹配0个或1 个x
*  例如(x*)                            匹配0个或任意多个x
+  例如(x+)                            匹配至少一个x
(xyz)+                                     匹配至少一个(xyz)
{m,n} 例如x{m,n}  n>=次数>=m            匹配最少m个、最多n个x
{n}                                        匹配前一项n次    
{n,}          匹配前一项n次,或者多次

六、常用正则表示==(128)==

1、检查邮政编码

var pattern = /[1-9][0-9]{5}/; //共6位数字,第一位不能为0
var str = '224000';
alert(pattern.test(str));
Copy after login

2、检查文件压缩包

var pattern = /[\w]+\.zip|rar|gz/; //\w 表示所有数字和字母加下划线
var str = '123.zip'; //\.表示匹配.,后面是一个选择
alert(pattern.test(str));
Copy after login

3、删除多余空格

var pattern = /\s/g; //g 必须全局,才能全部匹配
var reg=new RegExp('\\s+','g');
var str = '111 222 333';
var result = str.replace(pattern,''); //把空格匹配成无空格
alert(result);
Copy after login

4、删除空格

var pattern = /^\s+/; 
var str = ' goo gle ';
alert(str+" "+str.length);
var result = str.replace(pattern, '');
alert(result+" "+result.length);
pattern = /\s+$/; 
result = result.replace(pattern, '');
alert(result+" "+result.length);
pattern = /\s+/g; 
result = result.replace(pattern, '');
alert(result+" "+result.length);
5、简单的电子邮件验证
var pattern = /^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/;
var str = 'yc60.com@gmail.com';
alert(pattern.test(str));
var pattern = /^([\w\.\-]+)@([\w\.\-]+)\.([\w]{2,4})$/;
var str = 'yc60.com@gmail.com';
alert(pattern.test(str));
Copy after login

七、支持正则表达式的字符串方法

方法 描述
search 检索与正则表达式相匹配的第一个匹配项的索引。
match 找到一个或多个正则表达式的匹配。
replace 替换与正则表达式匹配的子串。
split 把字符串分割为字符串数组。
<script type="text/javascript">
 var s = "Abc123aBc";
 alert(s.search(/abc/gi)); 
 alert(s.search(/abc/gi)); // 即使设置的全局模式,每次search也是从开始向后查找
 //match方法和正则表达式的exec()方法的作用是一样的,但是match会一次性把所有的匹配放在一个数组中,全部返回
 alert(s.match(/abc/gi)); // Abc,aBc
 alert(s.replace(/[ab]/gi, "x"));   //把a或b替换成x
 var ss = s.split(/[0-9]+/gi); //用1个或多个数字切割。 Abc,aBc
 alert(ss);
</script>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

正则表达式的{n,m}量词如何使用

正则表达式小结(实战归纳)

The above is the detailed content of Detailed explanation of the use of the most basic regular expressions in JS. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!