const text ="mom and dad and baby";let pattern =/mom( and dad( and baby)?)?/gi;let matches = pattern.exec(text);// 返回包含 input 和 index 属性的数组,没找到则返回 null
console.log(matches.index);// 0
console.log(matches.input);// "mom and dad and baby"
console.log(matches[0]);// "mom and dad and baby"
console.log(matches[1]);// " and dad and baby"
console.log(matches[2]);// " and baby"
test()
5.2.3 RegExp 构造函数属性
无 Web 标准出处,不要在生产环境中使用
全 名
简 写
说 明
input
$_
最后搜索的字符串
lastMatch
$&
最后匹配的文本
lastParen
$+
最后匹配的捕获组
leftContext
$`
input 字符串中出现在 lastMatch 前面的文本
rightContext
$’
input 字符串中出现在 lastMatch 后面的文本
const text ="this has been a short summer";let pattern =/(.)hort/gi;if(pattern.test(text)){
console.log(RegExp.input);// "this has been a short summer"
console.log(RegExp.leftContext);// "this has been a "
console.log(RegExp.rightContext);// " summer"
console.log(RegExp.lastMatch);// "short"
console.log(RegExp.lastParen);// "s"}
const text ="this has been a short summer";let pattern =/(..)or(.)/gi;if(pattern.test(text)){
console.log(RegExp.$1);// "sh"
console.log(RegExp.$2);// "t"// 最多存储 9 个}