簡體   English   中英

當在 Python 中使用正則表達式之間有單詞時,如何提取特定關鍵字之后的下一行?

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

我想在匹配關鍵字總數后提取金額 495.65。 金額在下一行。 提前致謝!

總計:(僅迪拉姆四百九十六和六十五菲爾)

496.65

最好的問候,您批准建議並安排付款,因此我們將為您提供稅務發票。

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

output 是:(僅迪拉姆四百九十六和六十五 fils)

您可以匹配total:並在匹配該行的 rest 后匹配 1 個或多個換行符來捕獲組中的值。

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

解釋

  • \bTotal:.*匹配total:和該行的 rest
  • [\r\n]+匹配 1+ 個換行符
  • (\d+(?:\.\d+))捕獲組 1,匹配帶有可選小數部分的數字
  • \b一個詞的邊界

正則表達式演示| Python 演示

示例代碼

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

['496.65']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM