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

Regular expressions of JS basic series

黄舟
Release: 2017-02-20 14:09:14
Original
1355 people have browsed it

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!

Regular expressions of JS basic series

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, it is usually further processed using server scripts such as PHP, ASP.NET, and JSP. 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 object. There are two ways to create an object. Method:

2.1 Method 1: Use keyword new to create

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



Parameter 1: Regular expression model. 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 expression literals

var pa = /pattern/modifiers;
Copy after login


The two /s in the middle represent the regular expression pattern, and the last / is followed by the pattern modifier

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

Note: At this time, the mode and mode modifier can add 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 modifier ==(126)==
There are 3 pattern modifiers in JavaScript: g i u

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

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

u: Indicates that multiple lines can be matched.


4. Detailed explanation of regular expression methods==(127)==
There are two commonly used regular expression methods: test() and exec()


4.1 test() method
test(string)

Parameter: The string to be matched

Return value: Returns true if the match is successful, false if it fails

This method is very convenient to use when you only want to know whether the target string matches a certain pattern, but do not 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 Designed

Parameters: The string to be matched

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

Description of the return value array:

It is indeed an instance of Array.

But this array has two additional attributes: index and input

index: indicates the index of the matched string in the source string

input: indicates the matched Source string.

The first item in the array is the string that matches the entire pattern, and the other items are strings that match the capturing groups in the pattern

If there is no capturing group, there is only the first item in the array . We will talk about the concept of capturing groups later


<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


So if we want to find all matching strings, we can use a loop. The end condition is that the matching result is 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


Group. Tasks enclosed in () in regular expressions are a group. Groups can be nested.


<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 = &#39;224000&#39;;
alert(pattern.test(str));
Copy after login



2、检查文件压缩包

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



3、删除多余空格

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



4、删除空格

var pattern = /^\s+/; 
var str = &#39; goo gle &#39;;
alert(str+" "+str.length);
var result = str.replace(pattern, &#39;&#39;);
alert(result+" "+result.length);
pattern = /\s+$/; 
result = result.replace(pattern, &#39;&#39;);
alert(result+" "+result.length);
pattern = /\s+/g; 
result = result.replace(pattern, &#39;&#39;);
alert(result+" "+result.length);
5、简单的电子邮件验证
var pattern = /^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/;
var str = &#39;yc60.com@gmail.com&#39;;
alert(pattern.test(str));
var pattern = /^([\w\.\-]+)@([\w\.\-]+)\.([\w]{2,4})$/;
var str = &#39;yc60.com@gmail.com&#39;;
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



以上所述是小编给大家介绍的JS基础系列之正则表达式,更多相关内容请关注PHP中文网(www.php.cn)! 


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