如何用Python正则表达式提取特定关键词后隔行的目标内容?
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 :" (there.IGNORECASEflag 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

