简体   繁体   中英

Python regular expression re.match, why this code does not work?

This is written in 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.

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. What is the difference with or without bracket in pattern?

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

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

>>> 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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