[英]Python: How to extract a string right after another specified string
假设我有两个字符串列表,如下所示。
lst_1 = ['foo','bar','Invoice No: SME2324-AA']
lst_2 = ['trincas','hotel park','delivery date 12-sept-2019','invoice no: 11245']
目标:我想从这两个列表中提取发票编号。
到目前为止,我的方法:
lst_3 = [lst_1,lst_2]
txt=[]
for inv_no in lst_3:
for i in inv_no:
z = i
inv = re.search(r'Invoice (\S+) (.+?)',' '.join(z))
txt.append(inv)
当我想查看输出即txt
时,
[None, None, None, None, None, None, None, None]
我正在寻找的是
['SME2324-AA','11245']
我在这里错过了什么? 任何帮助,将不胜感激。
无需使用regex
,您可以通过以下方式尝试:
lst_3 = lst_1 + lst_2
txt=[]
for i in lst_3:
if 'invoice' in i.lower():
txt.append(i.split()[-1])
print (txt)
输出:
['SME2324-AA', '11245']
' '.join
使每个元素之间都带有空格。 (.+?)
以第一个匹配项(即非贪婪(.+?)
停止,并且r'Invoice...'
必然会因小写invoice
而失败。 append(inv)
实际上不会追加匹配结果。 您需要指定组: if inv: text.append(inv.group(2)
解决所有问题:
lst_3 = [lst_1,lst_2]
txt=[]
for inv_no in lst_3:
for i in inv_no:
z = i
inv = re.search(r'[Ii]nvoice (\S+) (.+)',z)
# group(1)^ ^group(2)
if inv:
txt.append(inv.group(2))
txt
输出:
['SME2324-AA', '11245']
您可以通过将re.findall
与re.IGNORECASE
使用来re.findall
re.IGNORECASE
:
import re
res = []
for i in lst_1 + lst_2:
res.extend(re.findall('invoice no: (.+)', i, re.IGNORECASE))
res
输出:
['SME2324-AA', '11245']
我们可以尝试将您的列表连接在一起形成一个字符串,然后使用re.findall
查找所有发票编号:
lst_1 = ['foo','bar','Invoice No: SME2324-AA']
lst_2 = ['trincas','hotel park','delivery date 12-sept-2019','invoice no: 11245']
lst_all = lst_1 + lst_2
inp = " ".join(lst_all)
invoices = re.findall(r'\binvoice no: (\S+)', inp, flags=re.IGNORECASE)
print(invoices)
打印:
['SME2324-AA', '11245']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.