如何在 javascript 正则表达式中匹配平衡分隔符?

2024-05-20

我原以为这个问题是不可能的;据我所知,Javascript 的正则表达式既没有递归插值,也没有漂亮的 .NET 平衡组功能。但问题就在那里,如问题 12 所示正则表达式 alf.nu http://regex.alf.nu:匹配平衡对< and >。除非集合中还有其他我没有得到的模式。

那么……这可能吗?如果是这样,怎么办?

NOTES:

  1. 我知道这对于真正的正则表达式来说是不可能的,但基于挑战,这似乎在 Javascript 的风格中是可能的(至少是不规则的,足以有反向引用)。我只是不知道有什么功能可以让他们做到这一点。

  2. 没有其他代码 - 该表单允许输入单个正则表达式,该正则表达式根据页面上的测试字符串进行评估。我想,我可以尝试破解该页面以摆脱正则表达式并进入原始 JS,但这似乎不符合此挑战的精神。

既然大卫问了,这里是测试字符串。较长的问题已被字符数截断,但问题的标题是“平衡”,完整的问题肯定支持“匹配”列具有平衡对的假设< and >而“不”栏则不然。

Match all of these…

<<<<<>><<>>><<... [62 chars]
<<<<<>><>><<><... [110 chars]
<<<<<>><>><>><... [102 chars]
<<<<<>><>>>><<... [88 chars]
<<<<<>>><<<>><... [58 chars]
<<<<<>>><<><>>... [152 chars]
<<<<<>>><<>><<... [42 chars]
<<<<<>>><>><<<>>>><<>>
<<<<<>>>><<<<>... [102 chars]
<<<<<>>>><<<><... [30 chars]
<<<<<>>>><><<<... [66 chars]
<<<<<>>>><><<<... [124 chars]
<<<<<>>>><>><<>>
<<<<><<>>><<<>... [34 chars]
<<<<>><<<>>>><... [92 chars]
<<<<>>><<<<>><>><<<>>>>>
<<<<>>><<<><<>>><><<>>>><<>>
<<<<>>><<><<<>... [84 chars]
<<<<>>>><<<><<... [52 chars]
<<<><<<>>>><<<... [50 chars]
<<<><<><>>>>
<<<><>><<<>>>>
<<<>><<<><<>>>... [44 chars]
<<<>><><<<><>>... [48 chars]
<<<>>><<><<<<>>>><<><<<>>>>>
<<><<<<>><>>>>... [60 chars]
<<>>
<<>><<<<<>>>>>... [54 chars]
<<>><<<<>><<<>... [74 chars]
<>
<><>

and none of these…

<
<<<<<<>>><<><>>>>>><<>
<<<<<>>><>>><<<>>>><>>
<<<<<>>>>>>
<<<<>><<<<<><<>><><<<<
<<<>><<<<><><><><
<<<>>>><><<<><>
<<><<<<><<><<>>><<
<<><<<>>>>><<
<<>>><<<>>
<><<<>><<>>><<>
<><<>>><<<><>><<<>>><<>>>><
<><<>>><><<<>
<><>><>>><><<<... [36 chars]
<>><><<<><>
<>>>>>><<<>><<>><><
<>>>>>>><<<
>
><
><<<>><><<<><<
><<<>>>><><<<<><>>><<><><<
><<><<<<><<<<>>>><
><><><<<>>>>>
><><>>><>><>
><><>>>><>>>>>>><>>><>>
><>><<<<<>>
><>><><><<>><<>>><<
><>>><>>>>><<><<<><>><>><<<
>><<<><<<<<<><>><<
>><>>><<<><>>><><<>><<><><<
>>>><>><>>>><>>><>><><
>>>>><<<>>>

I do not believe that this is possible in JavaScript, though it's hard to prove. For example, Java and PHP do not have the features that you mention (recursive interpolation, balancing groups), but this fascinating Stack Overflow answer https://stackoverflow.com/a/3644267/978917 shows how to match anbn using regexes in those languages. (Adapting that answer to the present case, the Java regex ^(?:(?:<(?=<*(\1?+>)))+\1)*$ should work. Correction: no, it's not that easily adapted.) But that answer depends on Java's support for the possessive quantifier ?+ (like ? except that you can't backtrack into it), and JavaScript doesn't have that.

也就是说,您可以通过编写以下代码来解决引用的难题:

^(?:<(?:<(?:<(?:<(?:<(?:<(?:<>)*>)*>)*>)*>)*>)*>)*$

最多可匹配七层嵌套。这是所有琴弦中最多的,所以这就是您所需要的。 (该页面上的其他几个谜题建议您作弊,因为它们要求一些技术上不可能的东西;因此,虽然一个优雅的解决方案显然更有吸引力,但没有理由假设存在一个解决方案。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 javascript 正则表达式中匹配平衡分隔符? 的相关文章

随机推荐