正则表达式获取指定字符串后的文本:匹配Total payment后的货币代码
Got it, let's sort out this regex issue you're having. You want to grab the "EUR" that follows "Total payment: 13214" in your target string, while ignoring any other similar "number + 3-letter code" structures elsewhere. Your current regex isn't working because it's using the wrong kind of lookaround and targeting the wrong part of the string.
Why Your Original Regex Fails
Your regex (?!<Total payment )(\d+) ([A-Z]){3,} has two key issues:
- The
(?!<...)is a negative lookbehind, which means it's looking for positions where the text before is NOT "Total payment " — exactly the opposite of what you need. - You're capturing the digits and individual letters instead of targeting the currency code directly, and the structure doesn't tie the code specifically to the "Total payment:" prefix.
Correct Regex Solutions
Here are two reliable approaches depending on your regex engine's capabilities:
Option 1: Positive Lookbehind (Cleanest, for engines that support it like Python, Java, .NET)
This regex directly matches the 3-letter currency code only if it's preceded by "Total payment: " plus one or more digits and a space:
(?<=Total payment: \d+ )[A-Z]{3}
(?<=Total payment: \d+ ): Positive lookbehind that verifies the text before the current position is exactly "Total payment: " followed by digits and a space.[A-Z]{3}: Matches the 3-letter uppercase currency code (like EUR) that you want to extract.
Option 2: Capturing Group (Works everywhere, including older engines like pre-ES2018 JavaScript)
If lookbehind isn't supported, wrap the currency code in a capturing group and extract that group's value:
Total payment: \d+ ([A-Z]{3})
- The entire regex matches the "Total payment: xxxxx EUR" sequence, and the
([A-Z]{3})captures just the currency code you need.
Example Usage (Python)
Here's how you'd implement this in code to get your desired result:
import re target_text = "Some text before and Total payment: 13214 EUR Signature:" # Using positive lookbehind result = re.search(r'(?<=Total payment: \d+ )[A-Z]{3}', target_text) if result: print(result.group()) # Output: EUR # Using capturing group result = re.search(r'Total payment: \d+ ([A-Z]{3})', target_text) if result: print(result.group(1)) # Output: EUR
Both methods will only match the "EUR" tied to the "Total payment:" line, ignoring any other similar structures in the text.
内容的提问来源于stack exchange,提问作者Rubyen

