[英]Python regex if match for more than one criteria in the same regex string
[英]Python regex, match more than one integer
下面的代码打印空白而不是“11”,我不知道为什么。 将[0-9]*
替换为[0-9]{1,2}
会打印“11”。 任何人都可以帮忙吗?
import re
test_string = 'cake_11xlfslijg'
pattern = '.*(?P<order>[0-9]*)'
result = re.compile(pattern).search(test_string)
if result:
print 'result'
print result.group('order')
else:
print result
尝试[0-9]+
。 *
转换为"zero or more" ,并且字符串开头有零个或多个数字。
你的正则表达式应该是这个
pattern = '(?P<order>[0-9]+)'
因为*
意味着:任意数量的重复,在您的正则表达式中.*
将匹配所有字符串,因为.
表示任何字符,即包括[0-9]
一个正则表达式模式需要有最少的锚点。
和 '。 ' 和 '[0-9] ',只有可选符号。
尝试
import re
for test_string in ( 'cake_11xlfslijg',
'cake_uuxlfslijg'):
pattern = '.*?(?P<order>[0-9]+)'
result = re.compile(pattern).search(test_string)
print test_string
print 'result: ',repr(result.group('order')) if result else result
print
给
cake_11xlfslijg
result: '11'
cake_uuxlfslijg
result: None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.