需要正则表达式来匹配动态确定的重复计数
我需要一个 ruby 正则表达式模式,该模式与包含字母(为简单起见,称“a”)的字符串匹配 n 次,然后在末尾匹配 n 次。
例如,它应该匹配“aaa3”、“aaaa4”等,但不匹配“a2”或“aaa1”等。
I need a ruby regexp pattern that matches a string containing a letter (for simplicity say 'a') n times and then n at the end.
For example, it should match "aaa3", "aaaa4" etc but not "a2" or "aaa1", etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可以用 Perl 做到这一点,但不能用 Ruby 做到。
有趣吧?
看看:http://ideone.com/ShB6C
I can do it in Perl, but not in Ruby.
Fun, eh?
Check it out: http://ideone.com/ShB6C
这在正则表达式中是不可能的,因为它不是常规语言(这很容易用 正则语言的泵引理证明)。我不确定 ruby 正则表达式比真正的正则表达式强大多少,但我怀疑它是否足够强大。您可以对其设置有限限制并陈述每种可能性,例如:
由于所有有限语言都是规则的,但是使用字符串操作来计算字母出现的次数然后解析字符串中的该整数会很容易那封信的最后一封之后。
That is not possible in regex since it is not a regular language (that's easy to prove with the Pumping Lemma for Regular Languages). I'm not sure how much more powerful ruby regex is than a true Regular Expression, but I doubt it's powerful enough for this. You can set a finite limit on it and state each possibility like:
Since all finite lanugages are regular, but it would be much easy to use string operations to count the number of times a letter appears and then parse for that integer in the string right after the last of that letter.
我刚刚醒来,所以对此持保留态度,但不是用单个正则表达式来做,一个简单的方法是
I just woke up, so take this with a grain of salt, but instead of doing it with a single regex, an easy way to do it would be