gpt4 book ai didi

Python 提取模式匹配

转载 作者:IT老高 更新时间:2023-10-28 21:11:28 26 4
gpt4 key购买 nike

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

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

someline abc
someother line
name my_user_name is valid
some more lines

我想提取单词 my_user_name。我做类似的事情

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>

我现在如何提取 my_user_name

最佳答案

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

>>> 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 提取模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com