繁体   English   中英

匹配数字和可变位数

[英]Match number with variable number of digits

我试图确定字符串是否匹配正则表达式模式:

expected = re.compile(r'session \d+: running')
string = "session 1234567890: running"
re.match(expected, string)

但是, re.match()始终返回None 我是否尝试错误地匹配小数? 该数字应为10位数字,但我想介绍一下它是多少位数字的情况。

编辑:字符串参数实际上是先前匹配的结果:

expected = re.compile(r'session \d+: running')
found = re.match(otherRegex, otherString)
re.match(expected, found.groups()[0])

当我打印found.groups()[0]的类型时,它会打印class str ;当我打印found.groups()[0] ,它将打印我期望的字符串: "session 1234567890: running" 这可能就是为什么它对我不起作用吗?

不,它不适合我:

In [219]: strs = "session 1234567890: running"

In [220]: expected = re.compile(r'session \d+: running')

In [221]: x=re.match(expected, strs)

In [222]: x.group()
Out[222]: 'session 1234567890: running'

在我的问题中,我已将字符串缩短到相关的部分。 实际的字符串有:

expected = re.compile(r'session \d+: running task(s)')
str = "session 1234567890: running(s)"
re.match(expected, str)

从来没有匹配的原因是因为'('')'字符是特殊字符,我需要对其进行转义。 现在的代码是:

expected = re.compile(r'session \d+: running task\(s\)')
str= "session 1234567890: running(s)"
re.match(expected, str)

对困惑感到抱歉

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM