如何用正则表达式提取字符串中带符号货币价格并排除非价格数字
Hey there, the issue with your current regex is that it’s looking for any numeric pattern, regardless of whether it’s attached to a currency symbol. That’s why it’s picking up the "2" from BED/BATH along with the actual price. Let’s fix that to only target prices paired with currency symbols!
The Solution Regex
To match prices that start with a currency symbol (and include the symbol in the match), use this:
[\$€£¥]\d{1,3}(?:,\d{3})*(?:\.\d{2})?
Breakdown of the Regex
Let’s break down each part so you understand how it works:
[\$€£¥]: Matches common currency symbols (add more like ₹, ₽, or CHF if you need to support other currencies)\d{1,3}: Starts with 1-3 digits (since most prices begin with up to 3 digits before the first thousand separator)(?:,\d{3})*: A non-capturing group that matches thousands separators (like,000) repeated any number of times—this handles values like120,000or1,234,567(?:\.\d{2})?: An optional non-capturing group for decimal cents (matches.00,.99, etc.)—this is optional because some prices don’t include decimals
Testing on Your Sample String
For your example:
"2 BED / 2 BATH for $120,000.00, what a deal!!!"
This regex will only match $120,000.00—no more random unrelated numbers cluttering your results.
Customization Tips
- If you need to support prices that use dots instead of commas for thousands separators (common in Europe), adjust the regex to handle both:
Just note this has edge cases—stick to the specific format your data uses if you can, for better accuracy.[\$€£¥]\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})? - If you want to ensure the currency symbol isn’t part of another word (e.g., avoiding something like
ABC$100), add a word boundary before the symbol:\b[\$€£¥]...
内容的提问来源于stack exchange,提问作者Misha Krul
相关产品推荐
相关产品推荐

