Python正则表达式re.match,为什么这段代码不起作用?

时间:2013-02-18 10:08:45

标签: python regex

这是用Python编写的,

import re
s='1 89059809102/30589533 IronMan 30 Santa Ana Massage table / IronMan 30 Santa Ana Massage table'
pattern='\s(\d{11})/(\d{8})'
re.match(pattern,s)

它没有返回。

我尝试关闭括号,

pattern='\s\d{11}/\d{8}' 

它仍会返回none

我的问题是:

  1. 为什么re.match找不到任何东西?
  2. 模式中有或没有括号有什么区别?

1 个答案:

答案 0 :(得分:21)

re.match“匹配”自字符串开头以来,但还有一个额外的1

使用re.search代替,它将“搜索”字符串中的任何位置。而且,在你的情况下,也找到了一些东西:

>>> re.search(pattern,s).groups()
('89059809102', '30589533')

如果您删除模式中的括号,它仍会返回有效的_sre.SRE_Match对象,但空groups

>>> re.search('\s\d{11}/\d{8}',s).groups()
()
相关问题