【问题标题】:Regex Grouping Stepped Explanation正则表达式分组分步说明
【发布时间】:2021-12-04 14:44:19
【问题描述】:
let quotedText = /'([^']*)'/;
console.log(quotedText.exec("she said 'hello'"));
//["'hello'", "hello"]

为什么hello会出现两次?

【问题讨论】:

  • The docs 说明索引[0] 是“匹配的完整字符串”,索引[1], ...[n] 是“括号内的子字符串匹配,如果有的话。”

标签: javascript regex ecmascript-6 regex-group


【解决方案1】:

结果中的第一个元素是完全匹配,第二个元素是first captured group。去掉括号() 只得到一个结果。

let quotedText = /'[^']*'/;
console.log(quotedText.exec("she said 'hello'"));

如果还想保留括号,可以使用如下图的非捕获组:

let quotedText = /'(?:[^']*)'/;
console.log(quotedText.exec("she said 'hello'"));

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多