js 正则表达式

1.分组

图1 分组类型

 

var str = ‘nice to meet you’;

(1)捕获型

var reg = / (nice) (to) (meet) (you) /;

reg.test(str);

 
$1 //nice

$2 //to

$3 //meet

$4 //you

嵌套分组的捕获捕获顺序:以左括号出现的顺序进行捕获。

var reg = / (nice (to)( meet (you)) )/;

var reg.test(str);


$1 //nice to meet you

$2 //to

$3 //meet you

$4 //you

(2)非捕获型

var reg = / (nice) to (?:meet) (you) /;

reg.test();


$1 //nice

$2 you

(3)正向前瞻型

var reg = / nice to meet (?=you)/;

reg.test( ‘nice to meet you’ ); //true

reg.test( ‘nice to meet her’ ); //false
var reg = / (nice to meet (?=you)) /;

reg.test(str);

$1 //nice to meet

(4)反向前瞻型

var reg = / nice to meet (?!you)/;
reg.test( ‘nice to meet you’ ); //false
reg.test( ‘nice to meet her’ ); //true

2.match()方法、exec()方法、search()方法、test()方法

(1)str.match(regexp)方法

   a.若正则表达式没有标志g

 正则表达式在字符串中执行一次匹配。如果没有找到匹配的字符串,返回null。如果找到匹配的字符串,返回一个数组,包括匹配的字符串和与正则表达式的子表达式匹配的字符串。此外,返回的数组还有两个属性:index和input。index表示匹配字符串的起始字符在str中的位置,input表示字符串str。

 

var str = 'nice to meet you nice to meet you nice to meet you',
      reg = /(to) (meet you)/;
var result = str.match(reg);
console.log(result); //["to meet you", "to", "meet you"]
console.log(result.index);//5
console.log(result.input);//nice to meet you nice to meet you nice to meet you

   b.若正则表达式有标志g

   正则表达式在字符串中执行全局匹配。若没有找到匹配的字符串,返回null。若找到了匹配的字符串,返回一个包含所有的匹配正则表达式的字符串组成的数组。

var str = 'nice to meet you nice to meet you nice to meet you',
      reg = /(to) (meet you)/g;
var result = str.match(reg);
console.log(result);//["to meet you", "to meet you", "to meet you"]
console.log(result.index);//undefined
console.log(result.input);//undefined

(2)reg.exec(str)方法

  a.若正则表达式没有标志g

  与str.match(regexp)方法返回的数组和属性相同。

  b.若正则表达式有标志g

  reg有一个lastIndex属性,表示上一次匹配文本之后的第一个字符的位置,初始值为0。exex()执行时,正则表达式从reg的属性lastIndex表示的位置开始搜索字符串,直到找到一个匹配的字符串,或到str结尾都没匹配到。若找到一个匹配的字符串,则返回一个数组,包括匹配的字符串和与正则表达式的子表达式匹配的字符串。返回数组有两个属性,input、index。index、input与match返回的index、input属性代表的含义相同。若到结尾都没有找到匹配的字符串,则返回null,重置lastIndex的值为0。下一次再执行exec()时,lastIndex为0开始搜索。这样构成一个循环。

var str = 'nice to meet you nice to meet you !',
    reg = /(to) (meet you)/;
console.log(reg.lastIndex);//0
var result1 = reg.exec(str);
console.log(result1);//["to meet you", "to", "meet you"]
console.log(result1.index);//5
console.log(result1.input);//nice to meet you nice to meet you !
console.log(reg.lastIndex);//16
var result2 = reg.exec(str);//
console.log(result2);//["to meet you", "to", "meet you"]
console.log(result2.index);//22
console.log(result2.lastIndex);//33
var result3 = reg.exec(str);
console.log(result3);//null
console.log(reg.lastIndex);//0
var result4 = reg.exec(str);
console.log(result4);//["to meet you", "to", "meet you"]
console.log(result4.index);//5
console.log(reg.lastIndex);//16
....

 (3)str.search(reg)方法

  不执行全局匹配,忽略标志g,总是返回第一个匹配的子字符串的起始位置。如果没有找到匹配的子字符串,返回-1。

 (4)reg.test(str)方法

      判断str中是否有匹配的子字符串,若有,返回true,若没有,返回false。

   

原文地址:https://www.cnblogs.com/fe-huahai/p/5387055.html