据我所知,JavaScript中没有命名的捕获组。获得类似功能的替代方法是什么?
当前回答
更新:它终于成为JavaScript (ECMAScript 2018)!
命名捕获组很快就会出现在JavaScript中。 提案已经进入第三阶段。
捕获组可以使用(?<name>…)语法在尖括号内指定名称,用于 任何标识符名称。日期的正则表达式可以是 写成/(? <一> \ d{4})——(? <月> \ d{2})——(? <天> \ d {2}) / u。每个名称 应该是唯一的,并遵循ECMAScript IdentifierName的语法。
的groups属性中的属性可以访问命名组 正则表达式结果。对组的编号引用是 也创建了,就像未命名组一样。例如:
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';
// result[0] === '2015-01-02';
// result[1] === '2015';
// result[2] === '01';
// result[3] === '02';
其他回答
ECMAScript 2018在JavaScript正则表达式中引入了命名捕获组。
例子:
const auth = 'Bearer AUTHORIZATION_TOKEN'
const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
console.log(token) // "AUTHORIZATION_TOKEN"
如果您需要支持旧的浏览器,您可以使用普通的(编号的)捕获组来完成您可以使用命名捕获组来完成的所有事情,您只需要跟踪数字—如果正则表达式中捕获组的顺序发生了变化,这可能会很麻烦。
我能想到的命名捕获组只有两个“结构性”优势:
In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex (see here for an example where this matters). But most regex flavors do not support this functionality anyway. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10. In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1, followed by a 0. In Perl, you can use ${1}0 in this case.
除此之外,命名捕获组只是“语法糖”。只有在真正需要时才使用捕获组,在所有其他情况下使用非捕获组(?:…)会有所帮助。
JavaScript最大的问题(在我看来)是它不支持冗长的正则表达式,这使得创建可读的复杂正则表达式变得容易得多。
Steve Levithan的XRegExp库解决了这些问题。
在ES6中,你可以使用数组解构来捕获你的组:
let text = '27 months';
let regex = /(\d+)\s*(days?|months?|years?)/;
let [, count, unit] = regex.exec(text) || [];
// count === '27'
// unit === 'months'
注意:
最后一个let中的第一个逗号跳过结果数组的第一个值,即整个匹配的字符串 .exec()后的||[]将在没有匹配时防止析构错误(因为.exec()将返回null)
更新:它终于成为JavaScript (ECMAScript 2018)!
命名捕获组很快就会出现在JavaScript中。 提案已经进入第三阶段。
捕获组可以使用(?<name>…)语法在尖括号内指定名称,用于 任何标识符名称。日期的正则表达式可以是 写成/(? <一> \ d{4})——(? <月> \ d{2})——(? <天> \ d {2}) / u。每个名称 应该是唯一的,并遵循ECMAScript IdentifierName的语法。
的groups属性中的属性可以访问命名组 正则表达式结果。对组的编号引用是 也创建了,就像未命名组一样。例如:
let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';
// result[0] === '2015-01-02';
// result[1] === '2015';
// result[2] === '01';
// result[3] === '02';
另一个可能的解决方案:创建一个包含组名和索引的对象。
var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };
然后,使用对象键来引用组:
var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];
这可以提高使用正则表达式结果的代码的可读性/质量,但不会提高正则表达式本身的可读性。
为捕获的组命名有一个好处:减少与复杂正则表达式的混淆。
这真的取决于你的用例,但也许漂亮地打印你的正则表达式会有所帮助。
或者您可以尝试定义常量来引用您捕获的组。
注释可能还有助于向阅读您代码的其他人展示您所做的工作。
至于其他的,我必须同意蒂姆的回答。