[英]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.