正则表达式中match和exec, test

AHuqihua 2020-06-13

// test
// 判断字符串是否满足某个匹配模式,满足的话,返回true,否则,返回false
let reg = /^a/
let str = ‘123abc‘

console.log(reg.test(str)) //false

// exec
// 用于检索字符串中的正则表达式的匹配。该函数返回一个数组,其中存放匹配的结果
// 如果未找到匹配,则返回值为null

let reg1 = /^a/

let str1 = ‘abc123abc‘

console.log(reg1.exec(str1)) //[ ‘a‘, index: 0, input: ‘abc123abc‘, groups: undefined ]

// match
// 也是用于匹配,分全局匹配和非全局匹配
// 非全局
let str3 =
  ‘Today is the 186th day of 2018,I must finish these 2 projects within 21 days.‘
let result1 = str3.match(/\d+/)
console.log(result1) 
// 结果 
// [
//   ‘186‘,
//   index: 13,
//   input: ‘Today is the 186th day of 2018,I must finish these 2 projects within 21 days.‘,
//   groups: undefined
// ]

// 全局
let str4 =
  ‘Today is the 186th day of 2018,I must finish these 2 projects within 21 days.‘
let result2 = str3.match(/\d+/g)
console.log(result2) 
// 结果 [ ‘186‘, ‘2018‘, ‘2‘, ‘21‘ ]

相关推荐