简体   繁体   English

当在 Python 中使用正则表达式之间有单词时,如何提取特定关键字之后的下一行?

[英]How to extract the next line after a specific keyword when there are words in between using regex in Python?

I want to extract the amount 495.65 after matching the keyword total.我想在匹配关键字总数后提取金额 495.65。 The amount is in next line.金额在下一行。 Thanks in advance!提前致谢!

Total:(Dirham Four Hundred Ninety Six and Sixty Five fils Only)总计:(仅迪拉姆四百九十六和六十五菲尔)

496.65 496.65

Best Regards, y approve the proposal and arrange the payment, accordingly we will provide you the tax invoice.最好的问候,您批准建议并安排付款,因此我们将为您提供税务发票。

    re.findall('(?<=total :)((.*){2})', string, re.IGNORECASE)

The output is: (Dirham Four Hundred Ninety Six and Sixty Five fils Only) output 是:(仅迪拉姆四百九十六和六十五 fils)

You can match total: and capture the value in a group by matching 1 or more newlines after matching the rest of the line.您可以匹配total:并在匹配该行的 rest 后匹配 1 个或多个换行符来捕获组中的值。

\bTotal :.*[\r\n]+(\d+(?:\.\d+))\b

Explanation解释

  • \bTotal:.* Match total: and the rest of the line \bTotal:.*匹配total:和该行的 rest
  • [\r\n]+ Match 1+ newlines [\r\n]+匹配 1+ 个换行符
  • (\d+(?:\.\d+)) Capture group 1, match a digit with an optional decimal part (\d+(?:\.\d+))捕获组 1,匹配带有可选小数部分的数字
  • \b A word boundary \b一个词的边界

Regex demo |正则表达式演示| Python demo Python 演示

Example code示例代码

import re

regex = r"\bTotal :.*[\r\n]+(\d+(?:\.\d+))\b"

test_str = ("Total :(Dirham Four Hundred Ninety Six and Sixty Five fils Only)\n\n"
    "496.65\n\n"
    "Best Regards,\n"
    "y approve the proposal and arrange the payment, accordingly we will provide you the tax\n"
    "invoice .")

print(re.findall(regex, test_str, re.IGNORECASE))

Output Output

['496.65']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中使用正则表达式提取字符串旁边的单词 - How to extract words next to a string using regex in python Python提取前3个单词和3个单词后带有正则表达式的特定单词列表 - Python extract 3 words before and 3 words after a specific list of words with a regex 如何逐行提取直到特定的关键字,然后声明为变量 - How to extract line after line till a specific keyword and then declare to a variable 如何使用python在正则表达式搜索后打印下一行 - How to print next line after regex search using python 如何在使用python在文本中找到关键字后提取一些先词 - how to extract few before words after finding a keyword in text using python 从特定单词中提取单词直到下一个标点符号[Python Regex] - Extract words from specific words until next punctuation mark [Python Regex] 在Python中使用正则表达式从字符串中提取具有特定字符的单词列表 - Extract list of words with specific character from string using regex in Python python 的正则表达式:如何在单词之间提取字符串? - Regex for python: how do I extract a string between words? 如何使用正则表达式在Python 3中查找特定字符串之后或之前的行? - How to find a line after or before a specific string in Python 3 using regex? 如何在Python中删除具有特定关键字的行后的后续行 - How to Delete Subsequent Line After A Line With Specific Keyword in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM