使用正则表达式的方法

一.方法

正则表达式可以被用于 RegExp 的 exec 和 test 方法以及 String 的 match 、replace、search 和 split 方法。

方法 描述
exec 一个在字符串中执行查找匹配的 RegExp 方法,它返回一个数组(未匹配到则返回 null)
test 一个在字符串中测试是否匹配的 RegExp 方法,它返回 true 或 false
match 一个在字符串中执行查找匹配的 String 方法,它返回一个数组,在未匹配到时会返回 null
matchAll 一个在字符串中执行查找所有匹配的 String 方法,它返回一个迭代器(iterator)
search 一个在字符串中测试匹配的 String 方法,它返回匹配到的位置索引,或者在失败时返回 -1
replace 一个在字符串中执行查找匹配的 String 方法,并且使用替换字符串替换掉匹配到的子字符串
split 一个使用正则表达式或者一个固定字符串分隔一个字符串,并将分隔后的子字符串存储到数组中的 String 方法

二.使用示例

2.1 exec

返回值是数组或null

const reg = new RegExp('[0-9]') // 创建一个正则表达式,匹配一个数字,等同于/[0-9]/
let result1 = reg.exec('A 1 2 Apple.') // 等同于 /[0-9]/.exec('A 1 2 Apple.')
console.log(result1) // [ '1', index: 2, input: 'A 1 2 Apple.', groups: undefined ]

let result2 = reg.exec('A Apple.')
console.log(result2) // null
2.2 test

返回值是true或false

const reg = new RegExp('^[0-9]+$') // 创建一个正则表达式,全部都是数字,等同于/^[0-9]+$/
let result1 = reg.test('123456abc') // 等同于/^[0-9]+$/.test('123456abc')
console.log(result1) // false

let result2 = /^[0-9]+$/.test('12345678999')
console.log(result2) // true
2.3 match

返回值是数组或null(返回正则表达式在字符串中首次匹配项的数组)
传入一个非正则表达式对象 regexp,则会使用 new RegExp(regexp) 隐式地将其转换为正则表达式对象,如下面传入的是一个字符串,会被转换成正则表达式对象。

const reg = new RegExp('^[0-9]+$') // 创建一个正则表达式,全部都是数字,等同于/^[0-9]+$/
let result1 = '123456abc'.match(reg) // 等同于'123456abc'.match(/^[0-9]+$/)
console.log(result1) // null

let result2 = '12345678999'.match(/^[0-9]+$/)
console.log(result2) // [ '12345678999', index: 0, input: '12345678999', groups: undefined ]

console.log('121231464'.match('65')) // null
console.log('121231464'.match('12')) // [ '12', index: 0, input: '121231464', groups: undefined ]
console.log('121231464'.match('64')) // [ '64', index: 7, input: '121231464', groups: undefined ]
2.4 matchAll

返回值是迭代器

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array);
// Expected output: Array [ 
// [ 'test1', 'e', 'st1', '1', index: 0, input: 'test1test2', groups: undefined ],
// [ 'test2', 'e', 'st2', '2', index: 5, input: 'test1test2', groups: undefined ]
// ]
2.5 search

返回值是匹配到的索引或-1(返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1)
传入一个非正则表达式对象 regexp,则会使用 new RegExp(regexp) 隐式地将其转换为正则表达式对象,如下面传入的是一个字符串,会被转换成正则表达式对象。

console.log('121231464'.search('12'))
// Expected output: 0

console.log('121231464'.search('64'))
// Expected output: 7

console.log('121231464'.search('65'))
// Expected output: -1

猜你喜欢

转载自blog.csdn.net/qq_43651168/article/details/130264535