[英]Extract a string after a text with regex in Python
我有一个 doc 文件,它具有以下结构:
This is a fairy tale written by
John Doe and Mary Smith
Auckland,somewhere
This story is awesome
我想提取两行文本,它们是:
John Doe and Mary Smith
Auckland,somewhere
和 append 使用正则表达式将这些值放入列表中。 我想提取的两行字总是在字里行间This is a fairy tale
, This story is awesome
了。 我怎样才能做到这一点? 我尝试了一些与before_keyword,keyword,after_keyword=text.partition(regex)
的组合,但一点运气都没有。
您可以使用带有re.DOTALL
的正则表达式来启用.
匹配任何字符,包括换行符。 一旦在两个分隔符之间有了文本,就可以使用另一个不带re.DOTALL
的正则表达式来提取至少包含一个非空白字符 ( \S
) 的行。
import re
lst = []
with open('input.txt') as f:
text = f.read()
match = re.search('This is a fairy tale written by(.*?)This story is awesome',
text, re.DOTALL)
if match:
lst.extend(re.findall('.*\S.*', match.group(1)))
print(lst)
给出:
[' John Doe and Mary Smith', ' Auckland,somewhere']
你可以从这个开始:
re.search(r'(?<=This is a fairy tale written by\n).*?(?=\n\s*This story is awesome)', s, re.MULTILINE|re.DOTALL).group(0)
并微调这个正则表达式。 re.MULTILINE
可以省略,因为您没有^
或$
反正,但re.DOTALL
需要 let .
也匹配换行符。 上面的正则表达式使用向前看和向后看(?<=)
, (?=)
。 如果您不喜欢这样,您可以使用括号代替捕获。
如果您可以从 docfile 创建字符串列表,则无需使用正则表达式。 只需执行这个简单的程序:
fileContent = ['This is a fairy tale written by','John Doe and Mary Smith','Auckland,somewhere','This story is awesome',
'Some other things', 'story texts', 'Not Important data',
'This is a fairy tale written by','Kem Cho?','Majama?','This story is awesome', 'Not important data']
authorsList = []
for i in range(len(fileContent)-3):
if fileContent[i] == 'This is a fairy tale written by' and fileContent[i+3] == 'This story is awesome':
authorsList.append([fileContent[i+1], fileContent[i+2]])
print(authorsList)
在这里,我只需检查'This is a fairy tale written by'
和'This story is awesome'
,如果找到,则在您的列表中显示 append 文本。
Output:
[['John Doe and Mary Smith', 'Auckland,somewhere'], ['Kem Cho?', 'Majama?']]
尝试改用它。 它应该匹配这两个字符串之间的任何内容。
re.search(r'(?<=This is a fairy tale).*?(?=This story is awesome)',text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.