美文网首页
正则表达式下篇

正则表达式下篇

作者: 懂会悟 | 来源:发表于2020-10-09 10:40 被阅读0次

1、和正则相关的一些方法

1、test

reg.test(str) 用来验证字符串是否符合正则 符合返回true 否则返回false

let str = 'abc'
let reg = /\w+/
console.log(reg.test(str)) 
// true
2、exec

reg.exec() 用来捕获符合规则的字符串

let str = 'abc123cba456aaa789'
let reg = /\d+/
console.log(reg.exec(str))
// ["123", index: 3, input: "abc123cba456aaa789"]
console.log(reg.lastIndex)
// lastIndex : 0

// lastIndex :记录的下一次捕获从哪个索引开始
// 当未开始捕获时,这个值为0
// 如果当前次捕获结果为null。那么lastIndex的值会被修改为0.下次从头开始捕获
// 而且这个lastIndex属性还支持人为赋值

// 解析["123",index:3,input:"abc123cba456aaa789"]
// "123" 表示我们捕获到的字符串
// index:3 表示捕获开始位置的索引
// input 表示原有的字符串

当我们用exec进行捕获时,如果正则没有加'g'标识符,则exec捕获的每次都是同一个,当正则中有'g'标识符时 捕获的结果就不一样了,我们还是来看刚刚的例子

let str = 'abc123cba456aaa789'
let reg = /\d+/g

console.log(reg.lastIndex)
// lastIndex : 0

console.log(reg.exec(str))
// ["123", index: 3, input: "abc123cba456aaa789"]

console.log(reg.lastIndex)
// lastIndex : 6

console.log(reg.exec(str))
// ["456", index: 9, input: "abc123cba456aaa789"]

console.log(reg.lastIndex)
// lastIndex : 12

console.log(reg.exec(str))
// ["789", index: 15, input: "abc123cba456aaa789"]

console.log(reg.lastIndex)
// lastIndex : 18

console.log(reg.exec(str))
// null
console.log(reg.lastIndex)
// lastIndex : 0

exec的捕获还受分组()的影响

let str = '2017-01-05'
let reg = /-(\d+)/g
console.log(reg.exec(str))

// ["-01", "01", index: 4, input: "2017-01-05"]

// "-01" : 正则捕获到的内容

// "01"  : 捕获到的字符串中的小分组中的内容

3、match

str.match(reg) 如果匹配成功,就返回匹配成功的数组,如果匹配不成功,就返回null

// match和exec的用法类似

let str = 'abc123cba456aaa789'
let reg = /\d+/
console.log(reg.exec(str))
// ["123", index: 3, input: "abc123cba456aaa789"]

console.log(str.match(reg))
// ["123", index: 3, input: "abc123cba456aaa789"]

// 当进行全局匹配时,二者的不同就显现出来.
let str_g = 'abc123cba456aaa789'
let reg_g = /\d+/g

console.log(reg_g.exec(str_g))
// ["123", index: 3, input: "abc123cba456aaa789"]

console.log(str_g.match(reg_g))
// ["123", "456", "789"]

当全局匹配时,match方法会一次性把符合匹配条件的字符串全部捕获到数组中,如果想用exec来达到同样的效果需要执行多次exec方法。

match和exec都可以受到分组()的影响,不过match只在没有标识符g的情况下才显示小分组的内容,如果有全局g,则match会一次性全部捕获放到数组中

let str = 'abc'
let reg = /(a)(b)(c)/
console.log(str.match(reg))
// ["abc", "a", "b", "c", index: 0, input: "abc"]
console.log( reg.exec(str) )
// ["abc", "a", "b", "c", index: 0, input: "abc"]

// 当有全局g的情况下
let str = 'abc'
let reg = /(a)(b)(c)/g
console.log(str.match(reg))
// ["abc"]

console.log( reg.exec(str) );
// ["abc", "a", "b", "c", index: 0, input: "abc"]
4、replace

string.replace(searchvalue, newvalue)

  • searchvalue 必须,规定子字符串或要替换的模式的 RegExp 对象。如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象,如: '/abc/gi'不会被解析为正则对象,因为它是字符串。
  • newvalue 必须。一个字符串值。规定了替换文本或生成替换文本的函数。
  • 返回值 String 一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。
let str = '讨论一下正则表达式中的replace的用法'
let reg = str.replace(/正则表达式/g, '')
console.log(reg)
// 讨论一下中的replace的用法

相关文章

网友评论

      本文标题:正则表达式下篇

      本文链接:https://www.haomeiwen.com/subject/mmansktx.html