Python 正则表达式匹配所有 5 位数字但没有更大的数字 [英] Python Regular Expression Match All 5 Digit Numbers but None Larger
本文介绍了Python 正则表达式匹配所有 5 位数字但没有更大的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对散布在整个 HTML 网页中的 5 位优惠券代码进行字符串匹配.例如,53232
、21032
、40021
等......我可以用 [0-9]{5}
,虽然这也匹配 6、7、8...n 位数字.有人可以建议我如何修改此正则表达式以匹配 only 5 位数字吗?
解决方案
>>>进口重新>>>s="四位数字 1234 五位数字 56789 六位数字 012345">>>re.findall(r"\D(\d{5})\D", s)['56789']
如果它们可以出现在开头或结尾,那么填充字符串比弄乱特殊情况更容易
<预><代码>>>>re.findall(r"\D(\d{5})\D", " "+s+" ")I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, 53232
, 21032
, 40021
etc... I can handle the simpler case of any string of 5 digits with [0-9]{5}
, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular expression to match only 5 digit numbers?
解决方案
>>> import re
>>> s="four digits 1234 five digits 56789 six digits 012345"
>>> re.findall(r"\D(\d{5})\D", s)
['56789']
if they can occur at the very beginning or the very end, it's easier to pad the string than mess with special cases
>>> re.findall(r"\D(\d{5})\D", " "+s+" ")
这篇关于Python 正则表达式匹配所有 5 位数字但没有更大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文