Python正则表达式re.match,为什么这段代码不起作用? [英] Python regular expression re.match, why this code does not work?

查看:72
本文介绍了Python正则表达式re.match,为什么这段代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用 Python 编写的,

导入重新s='1 89059809102/30589533 IronMan 30 Santa Ana 按摩台/IronMan 30 Santa Ana 按摩台'模式='\s(\d{11})/(\d{8})'重新匹配(模式,s)

它没有返回.

我试着去掉括号,

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

它仍然返回none.

我的问题是:

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

解决方案

re.match 从字符串的开头匹配",但是多了一个1.

使用 re.search 代替,它将搜索"字符串中的任何位置.而且,就您而言,还可以找到一些东西:

<预><代码>>>>re.search(pattern,s).groups()('89059809102', '30589533')

如果去掉pattern中的括号,它仍然会返回一个有效的_sre.SRE_Match对象,但是groups是空的:

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

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()
()

这篇关于Python正则表达式re.match,为什么这段代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆