简体   繁体   English

带有九对以上括号的正则表达式

[英]Regular expression with more than nine pairs of brackets

I have a regular expression with ten pairs of brackets. 我有一个带有十对方括号的正则表达式。 With RegExp.$n I need to access bracket pair 1, 2 and 10. In JS it's only possible to access the bracket pairs up to number 9. Since I need not to access pairs 3 to 9 is there a way to change the regular expression such those brackets don't count? 使用RegExp.$n我需要访问括号对1、2和10。在JS中,只能访问不超过9的括号对。由于我不需要访问3至9的括号对,因此可以更改常规这样的括号不算数吗? Then I could access bracket pair 9 by RegExp.$3 . 然后我可以通过RegExp.$3访问支架对9。 I'm also happy with any other solution to this problem. 对于此问题的任何其他解决方案,我也感到满意。 Thanks! 谢谢!

The match result is indexable by the group number (where there's always an implicit group 0 for the whole match): 匹配结果可通过组号索引(整个匹配中始终存在一个隐式组0 ):

> "banana".match(/()()()()()()()()()()(na)+/)[11]
"na"
> "banana".match(/()()()()()()()()()()(na)+/)[0]
"nana"

// Works with exec too
> /()()()()()()()()()()(na)+/.exec("banana")[11]
"na"

Note that within replace() , there doesn't seem to be a restriction on the group number: 请注意,在replace() ,似乎对组号没有限制:

> "banana".replace(/()()()()()()()()()()(na)+/, "[$11]")
"ba[na]"

To answer the other part of your question -- yes, it is indeed possible to have create what are called non-capturing groups using the (?:foo) syntax instead of (foo) . 要回答问题的另一部分-是的,确实有可能使用(?:foo)语法而不是(foo)来创建所谓的非捕获组

You can create non-capturing groups with ?: for things that you don't need to access later. 您可以使用?:创建非捕获组,以用于以后不需要访问的内容。

"rex".match(/(r)(?:e)(x)/)
// ["rex", "r", "x"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM