Python 提取模式匹配 [英] Python extract pattern matches

查看:40
本文介绍了Python 提取模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.7.1我正在尝试使用 python 正则表达式来提取模式中的单词

我有一些看起来像这样的字符串

someline abc另一条线名称 my_user_name 有效多几行

我想提取my_user_name"这个词.我做类似的事情

导入重新s = #那个大字符串p = re.compile("name .* is valid", re.flags)p.match(s) #this 给了我 <_sre.SRE_Match 对象在 0x026B6838>

我现在如何提取 my_user_name?

解决方案

您需要从正则表达式中捕获.search 寻找模式,如果找到,使用 group(index) 检索字符串.假设执行了有效检查:

<预><代码>>>>p = re.compile("name (.*) is valid")>>>结果 = p.search(s)>>>结果<_sre.SRE_Match 对象在 0x10555e738>>>>result.group(1) # group(1) 将返回第一个捕获(括号内的内容).# group(0) 将返回整个匹配的文本.'我的用户名'

Python 2.7.1 I am trying to use python regular expression to extract words inside of a pattern

I have some string that looks like this

someline abc
someother line
name my_user_name is valid
some more lines

I want to extract the word "my_user_name". I do something like

import re
s = #that big string
p = re.compile("name .* is valid", re.flags)
p.match(s) #this gives me <_sre.SRE_Match object at 0x026B6838>

How do I extract my_user_name now?

解决方案

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

这篇关于Python 提取模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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