gpt4 book ai didi

python - 正则表达式在文件中搜索确切的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:28 25 4
gpt4 key购买 nike

我已经查看了与此相关的其他问题,但我无法完全找到适合我的情况的答案。

我正在文件中搜索一个字符串。我想匹配确切的字符串,如果有匹配,就做一些事情。我正在尝试为字符串“author:”制定正则表达式。如果找到该字符串,请将其从行中删除,并给出其右侧的所有内容,删除所有空格。看看下面的代码有什么想法可以实现这一点吗?

metadata_author = re.compile(r'\bauthor:\b')
with open(tempfile, encoding='latin-1') as search:
for line in search:
result = metadata_author.search(line)
if result in line:
author = result.strip()
print(author)

最佳答案

我会使用lookbehind (对评论中提到的可能的点进行负面回顾):

metadata_author = re.compile(r'(?<=(?<!\.)\bauthor:).+')
with open(tempfile, encoding='latin-1') as search:
for line in search:
result = metadata_author.search(line)
if result:
author = result.group().strip()
print(author)

re.search 返回一个匹配对象,而不是字符串,因此要获取匹配字符串,您必须调用 result.group()

如果您想删除所有空格(而不仅仅是修剪),请使用 re.sub(r'\s*', '', result.group()) 而不是 result.group().strip().

关于python - 正则表达式在文件中搜索确切的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727916/

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