最近从新复习了一下正则表达式,如果平时没怎么使用的话,就会很容易忘记用法。编程这种东西的话,除了对概念基础须要扎实之外,还须要多练多写javascript
关于正则表达式的学习的,我看的是掘金做者 scq000 的文章: 正则表达式不要背java
我的感受文章里面写得是至关不错了,很容易理解。至于正则语句的编写,不少状况下都是须要结合当前环境设计的,须要的是思路和经验正则表达式
在这里的话,主要是记录下JavaScript中会用到正则表达式的几个函数,便于平常中的使用编程
检索返回一个字符串匹配正则表达式的的结果数组
返回值:函数
举两个例子:post
// 没有g标志的状况
let str = 'For more information, see Chapter 3.4.5.1'
let re = /see (chapter \d+(\.\d)*)/i
let found = str.match(re)
console.log(found)
// logs ['see Chapter 3.4.5.1',
// 'Chapter 3.4.5.1',
// '.1',
// index: 22,
// input: 'For more information, see Chapter 3.4.5.1']
// 'see Chapter 3.4.5.1' 是整个匹配。
// 'Chapter 3.4.5.1' 被'(chapter \d+(\.\d)*)'捕获。
// '.1' 是被'(\.\d)'捕获的最后一个值。
// 'index' 属性(22) 是整个匹配从零开始的索引。
// 'input' 属性是被解析的原始字符串。
复制代码
// 使用g标志的状况
let str = 'For more information, see Chapter 3.4.5.1, see Chapter 3.4.5.1'
let re = /see (chapter \d+(\.\d)*)/ig
let found = str.match(re)
console.log(found)
// logs ['see Chapter 3.4.5.1', 'see Chapter 3.4.5.1']
复制代码
能够看出二者的区别,在没有使用g标志的时候,在正则表达式中有分组(即有'('和')',详细看基础知识),也会将其捕获并放入结果中对应的位置。在使用g标志的时候,则只会将符合的结果放入结果中学习
在不传参数的时候,则返回[""],在传入一个非正则表达式对象做为参数的时候,则会使用new RegExp来隐式转换。固然了,通常状况下不会有这两种诡异的操做的吧ui
执行一个检索,用来查看正则表达式与指定的字符串是否匹配spa
返回值: true / false
let str = 'hello world!'
let result = /^hello/.test(str)
console.log(result)
// true
复制代码
当设置全局标志g的正则使用test方法,在执行时会改变正则表达式的lastIndex属性。若连续执行test,后续的执行会将从lastIndex处开始匹配字符串(遇false后lastIndex归0),如:
let regex = /foo/g;
// regex.lastIndex is at 0
regex.test('fooxxfooiifo') // true
// regex.lastIndex 3
regex.test('fooxxfooiifo') // true
// regex.lastIndex 8
regex.test('fooxxfooiifo') // false
// regex.lastIndex 0
复制代码
这是须要注意的地方,否则可能会因使用方式不对致使结果出错
在一个指定字符串中执行一个搜索匹配
返回值:
let re = /quick\s(brown).+?(jumps)/ig
let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog')
// !此时re的lastIndex会变成25
console.log(result)
// log ["Quick Brown Fox Jumps" 匹配的所有字符串
// "Brown" 括号中的分组捕获
// "Jumps" 括号中的分组捕获
// groups: undefined
// index: 4 匹配到的字符开始下标
// input: "The Quick Brown Fox Jumps Over The Lazy Dog"
// length: 3]
复制代码
当正则表达式使用全局标志g时,跟test同样都会每次改变正则的lastIndex,直到遇到结果为null时,lastIndex重置为0
执行正则表达式和 String 对象之间的一个搜索匹配 返回值:
let str = "hey JudE"
let re = /[A-Z]/g
let re2 = /[.]/g
console.log(str.search(re)) // 4
console.log(str.search(re2)) // -1
复制代码