找到你要的答案

Q:Simplifying a RegEx using a backreference

Q:简单的正则表达式使用反向引用

Consider the ECMAScript RegEx

/\s*((ABC|A)(/(ABC|A)+)*)\s*/i

which matches A/ABC

Using a backreference, I am trying to simplify it by rewriting it to

/\s*((ABC|A)(/\2+)*)\s*/i

but this only seems to match A/A

Why am I experiencing this behavior and can I use a backreference here to simplify the RegEx? (I am testing it online at http://www.regexr.com/)

考虑ECMAScript的正则表达式

/\s*((ABC|A)(/(ABC|A)+)*)\s*/i

哪个匹配

使用后向引用,我试图简化它通过重写它

/\s*((ABC|A)(/\2+)*)\s*/i

但这似乎只匹配A / A

为什么我要经历这样的行为,我可以在这里使用后向引用简化正则表达式?(我测试它在网上http://www.regexr.com/)

answer1: 回答1:

The reason that this is happening is because the new regex that you have will only A/A or A/AA or A/AAA, (any number of A's after the /). (Technically it'll also match ABC/ABC, or ABC/ABCABC)

The * after your (/\2+) capture group matches any number of the (/\2+) capture group. So unless you don't care what comes after the A/A (i.e. A/AFOO) then you could do /\s*((ABC|A)(/\2+).*)\s*/i which would match A/A(whatever here), (i.e. A/ABC, A/ADC, A/Afoobar)

Otherwise, I'd recommend sticking with the original regex.

这是发生的原因是因为你只会/或/ AA或AAA的/新的正则,(任意数量的后/)。(技术上它也会配合ABC,ABC,ABC /紧紧)

*(+ / + 2 +)捕获组匹配任何数量的(+ \ 2 +)捕获组。所以,除非你不在乎在一个/是什么(即/ aFoo)然后你可以做/的*((ABC |(一)/ 2 +)*)的* /我将/比赛(不管这里),(即ABC,一、ADC、一个/ afoobar)

否则,我建议坚持原来的正则表达式。

javascript  regex  backreference