简体   繁体   English

JavaScript正则表达式中的反向引用非捕获组

[英]Backreference non capture group in javascript regex

This is going to be a really short question... 这将是一个非常简短的问题...

Lets assume I have a regex like: 假设我有一个正则表达式,例如:

(Hello)(?:fooBar)

How can I backreference it using \\2? 如何使用\\ 2向后引用? I know this works with normal capturing groups and that a non capturing group only groups tokens together but if there is any work-around then I would be glad to know. 我知道这适用于普通捕获组,而非捕获组只能将令牌分组在一起,但是如果有任何解决方法,那么我将很高兴知道。

Edit: Problem is: 编辑:问题是:

I need to backreference to non capturing groups sometimes. 有时我需要向非捕获组反向引用。 For example there are moments where I really dont want that group to show up as a match but it shows up multiple times in the pattern which is why I prefer to backreference it. 例如,有时候我确实不希望该组显示为匹配项,但是在模式中它会显示多次,这就是为什么我更喜欢反向引用它。

As mentioned in the comments, a backreference applies only to a capture group. 如注释中所述,后向引用仅适用于捕获组。

But it sounds like your actual concern is with not repeating yourself. 但这听起来像您真正的担忧是不要重复自己。 In this case, you can construct the regex: 在这种情况下,您可以构造正则表达式:

const f = 'foobar';
const r = new RegExp(`Hello${f}blah${f}blah${f}blah`);

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

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