如何让 re.search 返回一个字符串?

Chi*_*Abs 11 python regex string

我正在尝试匹配文件行中的字符串并编写匹配项减去第一个和最后一个

import os, re

infile=open("~/infile", "r")
out=open("~/out", "w")
pattern=re.compile("=[A-Z0-9]*>")
for line in infile:
    out.write( pattern.search(line)[1:-1] + '\n' )
Run Code Online (Sandbox Code Playgroud)

问题是它说这Match是不可下标的,当我尝试添加.group()它时说Nonegroup has no attritube groupgroups() 返回.write需要一个元组等

知道如何.search返回一个字符串吗?

pra*_*nsg 9

re.search函数返回一个Match对象。

如果匹配失败,该re.search函数将返回 None。要提取匹配的文本,请使用Match.group方法。

>>> match = re.search("a.", "abc")
>>> if match is not None:
...     print(match.group(0))
'ab'
>>> print(re.search("a.", "a"))
None
Run Code Online (Sandbox Code Playgroud)

也就是说,使用组来查找匹配的所需部分可能是一个更好的主意:

>>> match = re.search("=([A-Z0-9]*)>", "=abc>")  # Notice brackets
>>> match.group(0)
'=abc>'
>>> match.group(1)
'abc'
Run Code Online (Sandbox Code Playgroud)

这个正则表达式然后可以像@WiktorStribi?ew 建议的那样与 findall 一起使用。


Wik*_*żew 4

=您似乎只需要和之间的字符串部分>。在这种情况下,在字母数字模式周围使用捕获组要容易得多,并将其与re.findallwill never return一起使用None,但在不匹配时只是一个空列表,或者如果找到则为捕获文本的列表。另外,我怀疑你需要空匹配,所以使用+而不是*

pattern=re.compile(r"=([A-Z0-9]+)>")
                      ^         ^
Run Code Online (Sandbox Code Playgroud)

进而

"\n".join(pattern.findall(line))
Run Code Online (Sandbox Code Playgroud)