0

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

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"。这可能是它对我不起作用的原因吗?

4

2 回答 2

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'
于 2012-10-24T16:47:04.407 回答
0

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

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

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

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

对困惑感到抱歉

于 2012-10-24T17:32:14.523 回答