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

如何用正则表达式提取收据中的最后价格?

Solution to Extract the Last Dollar Amount

Hey there! Let's figure out why your current regex isn't working and fix it.

Why Your Current Regex Fails

Your regex (?!\d+\s+TOTAL\s+)\$+\d+\.?\d+\s+(?=.*\$\d+\.?\d+) uses a positive lookahead (?=.*\$\d+\.?\d+) which tells the engine "only match this dollar amount if there's another dollar amount somewhere after it". That's exactly why it's picking $23.00 and $0.03—both have another dollar amount following them. The last amount $23.80 doesn't have any after it, so it gets excluded.

The Fix: Match the Last Dollar Amount

We need to reverse that logic: match a dollar amount only if there are no more dollar signs after it until the end of the string. Here's the regex to do that:

\$\d+(?:\.\d+)?(?!.*\$)

Let's break down what each part does:

  • \$: Matches the dollar sign (escaped because it's a special character in regex).
  • \d+: Matches one or more digits (the whole number part).
  • (?:\.\d+)?: An optional non-capturing group for the decimal part—\. matches the dot, \d+ matches one or more decimal digits, and ? makes this whole group optional (so it works for amounts like $5 or $5.00).
  • (?!.*\$): Negative lookahead that ensures there are no more dollar signs (\$) anywhere after the matched amount (.* matches any characters in between).

Testing with Your Input

For your input string " $23.00$0.03$23.80 ", this regex will only match $23.80 because it's the only dollar amount with no subsequent $ signs.

Alternative Approach: Capture the Last Amount with Greedy Matching

If you prefer using group capture, you can use this regex to greedily match everything up to the last dollar amount, then capture that final amount:

.*(\$\d+(?:\.\d+)?)

In this case, the actual amount will be in capture group 1 (you'll need to extract that group instead of the full match). This works because .* greedily consumes all characters until the last occurrence of the dollar amount pattern.

Hope this solves your problem!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:25:31