正则表达式分组步骤说明
Regex Grouping Stepped Explanation
let quotedText = /'([^']*)'/;
console.log(quotedText.exec("she said 'hello'"));
//["'hello'", "hello"]
why does hello appear twice?
结果中的第一个元素是完全匹配,第二个元素是 first captured group。去掉括号 ()
只得到一个结果。
let quotedText = /'[^']*'/;
console.log(quotedText.exec("she said 'hello'"));
如果你还想保留括号,可以使用如下所示的非捕获组:
let quotedText = /'(?:[^']*)'/;
console.log(quotedText.exec("she said 'hello'"));
let quotedText = /'([^']*)'/;
console.log(quotedText.exec("she said 'hello'"));
//["'hello'", "hello"]
why does hello appear twice?
结果中的第一个元素是完全匹配,第二个元素是 first captured group。去掉括号 ()
只得到一个结果。
let quotedText = /'[^']*'/;
console.log(quotedText.exec("she said 'hello'"));
如果你还想保留括号,可以使用如下所示的非捕获组:
let quotedText = /'(?:[^']*)'/;
console.log(quotedText.exec("she said 'hello'"));