乐趣的正则表达式 - 匹配具有等于2 ^ n

时间:2017-05-09 16:59:03

标签: regex

嘿那里!

我一直在寻找关于正则表达式的反思主题。我想要一个正则表达式,匹配单词列表中包含2 ^ n个字符的每个单词(其中n是自然数)。

为简单起见,我们假设一个单词只是o的序列 我们还要说列表由单词组成,后跟它们包含的字符数并用空格分隔 当然你不能使用这些数字,它是为了阅读目的!

例如:列表 o (1) ooo (3) oooooo (6) oooo (4) ooooooooo (9) oo (2) oooooooooooo (12) oooooooo (8)

我们应该有以下匹配:

matches : 'o', 'oo', 'oooo', 'oooooooo'


但是,你的正则表达式必须遵守一些规则:

  • 您不能使用递归
  • 您不能使用任何特定于某种语言(或几种语言)的功能


如果你设法找到一个在javascript中工作的(或技巧),它会很棒(虽然我不认为这是可能的)! 当然,它不需要使用javascript 解决问题不是重点,我只对如何解决问题感兴趣!

编辑:

可悲的是,没有人找到我想要的东西。问题仍然是答案,必须有好的答案!

顺便说一句,这就是我想出的,即使应该有更好的结果:

\b(?:o|(?:(?(1)\1|o)(?=((?(1)\1\1|o))))+\1)\b

演示here

3 个答案:

答案 0 :(得分:2)

我知道,你说没有递归,只是为了记录:

\b(?:o|(o(?1)?o))\b

Test it on regex101.com

让我们分解(所以我终于明白为什么它按预期工作了)! 忽略空格。

\b (?: o | ( o (?1)? o ) ) \b
\b                         \b # Word boundaries. Boring.
   (?: o |               )    # Just so it matches a single o, too.
           ( o (?1)? o )      # Now that's the interesting part.
           (           )      # Capture group 1
             o       o        # Matches an o each at the start and the end of the group
                              # -> the pattern matches from the outside to the inside.
               (?1)?          # Again the pattern of group 1, or nothing.
                              # -> Again one 'o' at the start and one at the end. Or nothing.

说实话,我不知道为什么它与oooooo(6)与三个两次递归不匹配。

修改:I asked a new question about it

答案 1 :(得分:2)

此正则表达式适用于支持捕获组1到9的反向引用的大多数正则表达式引擎。 但它最多只能捕获2 ^ 11 = 2048 o's

\bo{1,2}\b|\b(((((((((o{4})\9?)\8?)\7?)\6?)\5?)\4?)\3?)\2?)\1?\b

测试here

或者......我们可以硬编码2 ^ n个数字;)

\b(?:o|oo|o{4}|o{8}|o{16}|o{32}|o{64}|o{128}|o{256}|o{512}|o{1024}|o{2048})\b

答案 2 :(得分:0)

有证据表明你不能用常规语言或甚至无上下文语法来做到这一点:https://cs.stackexchange.com/questions/32338/show-that-0i-where-i-is-a-power-of-2-is-not-context-free

所以我相信没有后向引用或任何复杂扩展的正则表达式是不可能创建的。

根据此http://nikic.github.io/2012/06/15/The-true-power-of-regular-expressions.html,具有反向引用的正则表达式是NP完全的,因此反向引用应该足以使正则表达式工作。