正则表达式匹配规则
正则表达式的匹配规则可以看另外一篇文章:https://blog.csdn.net/qq_36754767/article/details/89857183
RegExp
JavaScript 可以通过构造函数RegExp构造正则表达式(Regular Express)
var pattern1=new RegExp('ain')
使用元字符匹配时需要添加转义符 \
也可以直接进行创建,使用 / 包裹匹配规则,下边示例匹配内容同上边正则表达式:
var pattern2=/ain/
修饰符
修饰符 | 描述 |
---|---|
i | 忽略大小写 |
g | 全局匹配 |
m | 多行匹配 |
RegExp 对象方法
- exec
exec 方法用于检测字符串中指定的值。返回检测到的值并返回检测值所在的位置.类似与字符串的match方法,不同的是str.match返回获取的所有值组成的数组,re.exec每次只返回一个匹配结果,返回结果取决于调用的次数var str="Is this his"; var pattern=/is/ig console.log(pattern.exec(str)) console.log(pattern.exec(str)) console.log(pattern.exec(str)) //["Is", index: 0, input: "Is this his", groups: undefined] //["is", index: 5, input: "Is this his", groups: undefined] //["is", index: 9, input: "Is this his", groups: undefined]
正则表达式有一个属性lastIndex用于标记下次开始查找的位置 pattern.lastIndex ,如果匹配不到结果了,则lastIndex重置为0,如果继续调用则重复
- test
用于检测指定值,检索到返回true,未检测到返回falsevar str="Is this his"; var pattern=/is/ig console.log(pattern.test(str)) //true
字符串的正则方法
-
search
search() 方法用于检索字符串中指定值,与字符串的
indexOf()
方法类似,检索成功返回指定值所在位置,否则返回-1var str="Is this his"; var pattern=/is/ig console.log(str.search(pattern)) //0
-
match
找到一个或多个与正则表达式相匹配的值,存放在数组中,未找到返回null
var str="Is this his"; var pattern=/is/ig console.log(str.match(pattern)) //(3) ["Is", "is", "is"]
-
replace
替换字符串中符合要求的值,下面示例使用正则去掉字符串的所有数字
var str="lga53ghaolniwoa51ga5"; var re=/\d+/g; var res= str.replace(re,'') ; console.log(res); //lgaghaolniwoaga
4.split
以正则表达式匹配结果作为分割符进行分割,下面示例使用以数字作为分割符分割字符串
var str="lga53ghaolniwoa51ga";
var re=/\d+/g;
var res= str.split(re) ;
console.log(res);
//(3) ["lga", "ghaolniwoa", "ga"]