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

时间:2021-12-16 15:47:28

This is written in Python,

这是用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)

it returns none.

它返回none。

I tried taking the brackets off,

我试着把括号去掉,

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

It still returns none.

它仍然没有回报。

My questions are:

我的问题是:

  1. Why the re.match does not find anything?
  2. 为什么。match什么都找不到?
  3. What is the difference with or without bracket in pattern?
  4. 在模式中有或没有括号的区别是什么?

1 个解决方案

#1


18  

re.match "matches" since the beginning of the string, but there is an extra 1.

从字符串开始匹配“matches”,但还有一个额外的1。

Use re.search instead, which will "search" anywhere within the string. And, in your case, also find something:

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

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

If you remove the brackets in pattern, it will still return a valid _sre.SRE_Match, object, but with empty groups:

如果删除模式中的括号,它仍然返回一个有效的_sre。SRE_Match,对象,但组为空:

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

#1


18  

re.match "matches" since the beginning of the string, but there is an extra 1.

从字符串开始匹配“matches”,但还有一个额外的1。

Use re.search instead, which will "search" anywhere within the string. And, in your case, also find something:

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

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

If you remove the brackets in pattern, it will still return a valid _sre.SRE_Match, object, but with empty groups:

如果删除模式中的括号,它仍然返回一个有效的_sre。SRE_Match,对象,但组为空:

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