在 JavaScript 正则表达式中命名捕获组? [英] Named capturing groups in JavaScript regex?

查看:24
本文介绍了在 JavaScript 正则表达式中命名捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,JavaScript 中没有命名捕获组这样的东西.获得类似功能的替代方法是什么?

As far as I know there is no such thing as named capturing groups in JavaScript. What is the alternative way to get similar functionality?

推荐答案

ECMAScript 2018 引入了 named将组捕获到 JavaScript 正则表达式中.

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

示例:

  const auth = 'Bearer AUTHORIZATION_TOKEN'
  const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
  console.log(token) // "Prints AUTHORIZATION_TOKEN"

如果您需要支持较旧的浏览器,您可以使用普通(编号)捕获组执行命名捕获组可以执行的所有操作,您只需要跟踪数字 - 如果捕获顺序可能会很麻烦group 在您的正则表达式更改中.

If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes.

我能想到的命名捕获组只有两个结构"优势:

There are only two "structural" advantages of named capturing groups I can think of:

  1. 在某些正则表达式风格(.NET 和 JGSoft,据我所知)中,您可以对正则表达式中的不同组使用相同的名称(参见此处的示例,了解这很重要).但无论如何,大多数正则表达式都不支持此功能.

  1. 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.

如果您需要在被数字包围的情况下引用编号的捕获组,则可能会遇到问题.假设您想在数字上加一个零,因此想用 $10 替换 (d).在 JavaScript 中,这会起作用(只要您的正则表达式中的捕获组少于 10 个),但 Perl 会认为您正在寻找反向引用编号 10 而不是编号 1,后跟一个 0.在 Perl 中,您可以在这种情况下使用 ${1}0.

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.

除此之外,命名的捕获组只是语法糖".仅在您真正需要它们时才使用捕获组,而在所有其他情况下使用非捕获组 (?:...) 会有所帮助.

Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances.

JavaScript 的更大问题(在我看来)是它不支持冗长的正则表达式,这会使创建可读、复杂的正则表达式变得容易得多.

The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier.

Steve Levithan 的 XRegExp 库 解决了这些问题.

这篇关于在 JavaScript 正则表达式中命名捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆