Python中典型的数羊正则表达式问题
晚上,我通常在祈祷后数羊来帮助我入睡。现在我想要一个正则表达式,来帮助我正确地计算这些羊。我希望以下这些字符串能够匹配:
0
1sheep
2sheepsheep
3sheepsheepsheep
等等。
那么,这个正则表达式应该是什么呢?
我想要的类似于 '(\d+)(sheep){\1}'
,如果 {\1}
能够实现我想要的效果的话。
如果我把羊成对地数(比如 1sheepsheep
和 2sheepsheepsheepsheep
),那么这个正则表达式又该怎么写呢?
3 个回答
1
你可以使用正则表达式来提取数字,然后用这个数字来编写第二个正则表达式,配合重复操作符使用:
import re
theString = '2sheepsheep'
rx = re.compile(r'^(\d+)(sheep)*$')
m = rx.match(theString)
rx = re.compile(r'^(\d+)(sheep){' + m.group(1) + '}$')
# If you count in pairs, you can just change that to:
rx = re.compile(r'^(\d+)(sheepsheep){' + m.group(1) + '}$')
2
这件事不能仅仅依靠正则表达式来完成;你应该先找到字符串开头的数字,然后再动态生成一个正则表达式来匹配其余部分。可以看看其他回答中的代码示例。
我觉得用Perl的正则表达式是可以做到的(搜索一下(?PARNO)
)。这可能就是我不喜欢Perl的原因。
3
Python的正则表达式引擎不支持把匹配到的子表达式解析成重复次数,我觉得用正则表达式也不应该这样做。
最好的办法是把正则表达式的匹配和代码检查结合起来:
rx = re.compile(r'^(\d+)((?:sheep)*)$')
m = rx.match(theString)
if m and len(m.group(2)) == 5 * int(m.group(1)):
print ("Matched")