You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则表达式提取特定关键词后隔行的目标内容?

Fixing Regex to Extract Amount After "Total :"

Hey there! I see you're trying to pull the numeric amount that comes after "Total :" in your text, but your current regex is grabbing the written-out currency description instead. Let's fix that up.

The Issue with Your Current Regex

Your regex re.findall('(?<=total :)((.*){2})', string, re.IGNORECASE) uses greedy matching (.*) repeated twice, which just captures whatever text follows "Total :" instead of targeting the specific decimal amount we care about. It doesn't distinguish between the written currency text and the numeric value we need.

Solution: Target the Numeric Amount Directly

We need to adjust the regex to skip over the written currency details and capture the decimal amount specifically. Here's a working approach:

import re

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

# Regex to capture the decimal amount after "Total :"
amount = re.findall(r'(?<=Total :).*?(\d+\.\d+)', text, re.IGNORECASE)
print(amount)  # Output: ['496.65']

Breakdown of the Regex:

  • (?<=Total :): A positive lookbehind to ensure we start matching right after "Total :" (the re.IGNORECASE flag makes this work for "total :", "Total :", etc.).
  • .*?: Non-greedy match of any characters—this stops as soon as it hits the next part we want to capture, so it doesn't gobble up the numeric amount.
  • (\d+\.\d+): Captures the exact numeric amount: one or more digits (\d+), followed by a decimal point (\.), then one or more digits (\d+).

Simpler Alternative

If you don't need the lookbehind, you can use this shorter version—it works because findall returns the content of captured groups by default:

amount = re.findall(r'Total :.*?(\d+\.\d+)', text, re.IGNORECASE)

Either way, you'll get the exact numeric amount you're targeting instead of the written-out currency description.

内容的提问来源于stack exchange,提问作者M_Arora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:24:04