js中的正则表达式

1.正则表达式的创建

js创建正则表达式有两种方式(我们一般会使用第一种):

1.通过类似Perl的语法:

let regexp1 = /pattern/flags

其中pattern是任何简单或者复杂的表达式,可以包含字符类,限定符,分组,向前查找以及反向引用。

flag支持:g(全局匹配,找到第一个匹配项后还会继续往后查找),i(不区分大小写),m(多行模式,找完一行后还会找下一行)

例:

let pattern = /at/g;

2.通过使用RegExp构造函数

let regexp2 = new RegExp(string,flag)

RegExp构造函数支持两个参数,参数都需要传字符串

例:

let pattern = new RegExp("at","g");

二.关于pattern的使用

pattern中使用的方括号,元字符,量词使用的方法见https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions

三.RegExp对象的方法

1.test()方法:检索字符串中指定的值。返回 true 或 false

    var pattern = /[hf]ello/g,
        str = 'hello';
    pattern.test(str); //true
    pattern = /[ef]ello/g;
    pattern.test(str); //false

2.exec() 方法:用于检索字符串中的正则表达式的匹配。返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。

var pattern = /[hf]ello/g,
      str = 'hello';
str = 'hello fello ello';
pattern.exec(str); //["hello", index: 0, input: "hello fello ello", groups: undefined]
pattern.lastIndex //5
pattern.exec(str); //["fello", index: 6, input: "hello fello ello", groups: undefined]
pattern.lastIndex //11
pattern.exec(str); //null
pattern.lastIndex //0

注意:如果在一个字符串中完成了一次模式匹配之后要开始检索新的字符串,就必须手动地把 lastIndex 属性重置为 0。

var pattern = /[hf]ello/g,
        str = 'hello';
str = 'hello fello ello';
pattern.exec(str);
//由于此时pattern.lastIndex=5,所以会从索引为5的地方开始匹配,因此下面这个会返回null
pattern.exec('hello');//null

因此需要先设置pattern.lastIndex = 0;再将该模式应用到新的字符串。

 3.compile()方法:用于改变和重新编译正则表达式

function CompileDemo(){
   var rs;
   var s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp"
   // Create regular expression for uppercase only.
   var r = new RegExp("[A-Z]", "g");
   var a1 = s.match(r)              // Find matches.
   // Compile the regular expression for lowercase only.
   r.compile("[a-z]", "g");
// Find matches.
   var a2 = s.match(r)              
   return(a1 + "
" + a2);
}

备注:compile 方法将 pattern 转换为内部的格式,从而执行得更快。例如,这允许在循环中更有效地使用正则表达式。当重复使用相同的表达式时,编译过的正则表达式使执行加速。然而,如果正则表达式发生更改,则这种编译毫无益处。

四.支持正则表达式的 String 对象的方法

1.search()方法:检索与正则表达式相匹配的子字符串。返回匹配到的子字符串的起始位置。

    var pattern = /[hf]ello/g,
        str = 'ss hello fello';
    str.search(pattern);//3

2.match()方法:找到一个或多个正则表达式的匹配。返回存放匹配结果的数组(该数组的内容依赖于 regexp 是否具有全局标志 g,不管有没有全局标志g),如果没找到都返回null

有全局标志g:

    var pattern = /[hf]ello/g,
        str = 'ss hello fello';
    str.match(pattern);// ["hello", "fello"]

无全局标志g(此时返回有点像regExp对象的exec方法):

    var pattern = /[hf]ello/,
        str = 'ss hello fello';
    str.match(pattern);//["hello", index: 3, input: "ss hello fello", groups: undefined]

3.replace(pattern,str)方法:替换一个与正则表达式匹配的子串。返回一个新的字符串(被模式匹配后的)

    var pattern = /[hf]ello/g,
        str = 'ss hello fello';
    str.replace(pattern,'world');//"ss world world"

4.split()方法:用参数中的字符串或者正则表达式来分割指定字符串。返回一个被字符串或者正则表达式分割过的数组。

    var pattern = /[hf]ello/g,
        str = 'ss hello fello';
    str.replace(pattern,'world');//["ss ", " ", ""]

 五.综合应用

1.姓名验证

var pattern = /^[u4E00-u9FA5]{1,4}(.?)[u4E00-u9FA5]{1,4}$/,
    str = '好好是·哈哈';
pattern.test(str);//true

可支持”好好·好好“这种格式的姓名。

2.手机号校验

var pattern = /^1[3,4,5,7,8,9][0-9]{9}$/,
    str = '13566666666';
pattern.test(str); //true

解释一下,pattern中的表达式表示第一位以1开头,第二位为3,4,5,67,8,9中的一个,后九位为0~9中的数字。具体量词和方括号等的含义还是看这里 http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp

开头的^和结束的$是必须的,加^$的话就代表把整个要匹配的字符串当成一个整体做一次匹配,而不加则一个字符串可以匹配多次,只能代表这个字符串中有符合条件的并不代表改字符串符合条件。

3.身份证校验

十八位身份证校验:

// 前六位:[1-9]d{5}
// 年份(1900-2099)(19|20)d{2}
// 月日(例子上的是闰年,如果平年的话把后面的02(0[1-9]|[1-2][0-9])改成02(0[1-9]|1[0-9]|2[0-8])即可):( (01|03|05|07|08|10|12)(0[1-9]|[1,2][0-9]|3[0-1]) | (04|06|07|11)(0[1-9]|[1,2][0-9]|30) | 02(0[1-9]|[1-2][0-9]) )
// 三位顺序码:[0-9]{3}
// 校验码(0-9或者X或者x):[0-9Xx]

var pattern = /^[1-9]d{5}(19|20)d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|07|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
var str = '23333319990223283X'; pattern.test(str); //true

十五位身份验证思路跟这个类似,大家可以自己试一下。

4.标签的匹配:

例:a标签的匹配

var pattern = /<a[^>]+href="([^"]*)"[^>]*>([sS]*?)</a>/
var str = '<a title="title" href="//www.baidu.com" class="hh"></a>';
pattern.test(str); //true

解释一下,其中

<a 表示匹配a标签的开始,
[^>]+ 匹配非>字符的一到多个任意字符
href="([^"]*)" 匹配href的值,并且将匹配到的值捕获到分组中
[^>]* 匹配href后除了>字符0到多个任意字符
([sS]*?) 匹配任意字符并捕获到组中(包含空格和非空格字符,非贪婪匹配,也可以用.?但是.不能包含空行)

上面两个分组的作用是方便匹配到相应的分组后获取他,可用exec()方法获取

pattern.exec(str); // ["<a title="title" href="//www.baidu.com" class="hh" ></a>", "//www.baidu.com", "", index: 0, input: "<a title="title" href="//www.baidu.com" class="hh" ></a>", groups: undefined]

  匹配img标签并且取出其中的title

function filterTagInContent(content){
    var reg = /<img title="(.*?)" [^>]*>/;
    var matches = {};
    //取出img标签中的title来替换img标签
    while(matches = reg.exec(content)){
        var imgTag = matches[0];
        var title = matches[1] || ''
        content = content.replace(imgTag,title);
    }
    return content;
}
filterTagInContent('嘎嘎嘎嘎嘎嘎<img title="[好好]" src="111"/>哈哈哈哈'); //"嘎嘎嘎嘎嘎嘎[好好]哈哈哈哈"

         应用实例先说这么多,到后面用到再添加。



原文地址:https://www.cnblogs.com/luoyanan/p/9134006.html