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

查看:114
本文介绍了在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推出命名捕获组到JavaScript正则表达式。

ECMAScript 2018 introduces named capturing groups into JavaScript regexes.

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

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天全站免登陆