使用正则表达式检查字符串中的条件

时间:2015-02-21 08:13:03

标签: python regex

我有一个包含两个逗号分隔数字的字符串;像这样:7878781,20。我想检查第一个号码;如果它以7878开头,则第二个数字应为20,否则逗号后面的第二个数字的长度应介于13到19之间。我想用regex一行来完成;如果它是可能的!有什么想法吗?

为了澄清,我想举一些例子;这些线和类似的线应匹配:

7878454545,20
78858558854545,3245697412356

这些行和类似的行不应该匹配:

184848,455
7878787878,45
488455784
4874854848885

我尝过^(?:7878\d*,20|\d{13,19})$^7878\d+,20|[\d]{13,19}$;两者都匹配4874854848885,但它们与87788,12345678912348不匹配。

2 个答案:

答案 0 :(得分:3)

你不需要太聪明。使用简单的东西可以解决问题:

    m = re.match(r'^(7878\d*,20)|(\d+,\d{13,19})$', s)
    #                ^^^^^^^^^^ ^ ^^^^^^^^^^^^^
    #   if first number starts  o  two numbers, the
    #     with 7878 the second  r  second being between
    #      number should be 20     13 and 19 digits long

鉴于您的测试用例:

import re

ts = [
"7878454545,20",
"78858558854545,3245697412356",
"184848,455",
"7878787878,45",
"488455784",
"4874854848885",
]

for s in ts:
    m = re.match(r'^(7878\d*,20)|(\d+,\d{13,19})$', s)
    print(s, m is not None)

产:

7878454545,20 True
78858558854545,3245697412356 True
184848,455 False
7878787878,45 False
488455784 False
4874854848885 False

答案 1 :(得分:0)

这种模式可以达到你想要的效果:

^(78)+[^(78)]+\d+,(20|\d{13,19})$
下面的

演示:

https://regex101.com/r/wF3tD3/4