匹配编号与可变位数

时间:2012-10-24 16:43:56

标签: python regex

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

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"。这可能就是为什么它不适合我?

2 个答案:

答案 0 :(得分:1)

没有它没有,它对我来说很好:

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'

答案 1 :(得分:0)

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

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)

对不起有困惑

相关问题