Python正则表达式匹配字符串的中间 [英] Python regex match middle of string

查看:193
本文介绍了Python正则表达式匹配字符串的中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 字符串,我正在尝试提取它.我有一个有趣的问题:

<预><代码>>>>s="SKU 9780136058281, (ASIN B00A2KNZ2S, (装订商家:'平装书'/'精装书'))">>>打印(重新匹配('ASIN',s))没有任何>>>打印(重新匹配('SKU',s))<_sre.SRE_Match 对象;span=(0, 3), match='SKU'>

我正在尝试在 ASIN 后面添加一个数字.我仍然看不到明显的问题.它匹配行的开头,但不在中间.

解决方案

你需要使用 re.search分组注意 re.match 匹配字符串开头的模式:

<预><代码>>>>s="SKU 9780136058281, (ASIN B00A2KNZ2S, (装订商家:'平装书'/'精装书'))">>>进口重新>>>re.search(r'SKU (\d+)',s).group(1)'9780136058281'

r'SKU (\d+) 将匹配 SKU 之后长度为 1 或更多的任何数字组合 (\d)和一个空间!

I have a python string, that I'm trying to extract. I have a interesting issue:

>>> s="SKU 9780136058281, (ASIN B00A2KNZ2S, (binding Merchant: 'paperback' / 'hardcover'))"
>>> print(re.match('ASIN', s))
None
>>> print(re.match('SKU', s))
<_sre.SRE_Match object; span=(0, 3), match='SKU'>

I'm trying to mach a the number after ASIN. I can't still see a obvious problem. Its matching the beginning of the line, but not in the middle.

解决方案

You need to use re.search and grouping,and Note that re.match match the pattern from beginning of the string :

>>> s="SKU 9780136058281, (ASIN B00A2KNZ2S, (binding Merchant: 'paperback' / 'hardcover'))"
>>> import re
>>> re.search(r'SKU (\d+)',s).group(1)
'9780136058281'

r'SKU (\d+) will match any combination of digits (\d) with length 1 or more that came after SKU and a space!

这篇关于Python正则表达式匹配字符串的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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