你好!
我一直在寻找关于正则表达式的反射主题。我想要一个正则表达式来匹配单词列表中包含 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
最佳答案
我知道,你说没有递归,但只是为了记录:
\b(?:o|(o(?1)?o))\b
让我们对其进行分解(这样我终于可以理解为什么它会按预期工作)! 忽略空格。
\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) 和 three 两个递归。
关于有趣的正则表达式 - 匹配字符数等于 2^n 的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875776/