正则表达式需求:移除货币格式中的小数点及小数部分
Solution to Strip Currency Decimal Separators and Fractional Parts
Got it, let's fix this for you! The issue with your current regex is that it only targets the final decimal point and its trailing digits, leaving the earlier separators (like the . in 60.000.00) intact. Here's how to handle both scenarios in one go:
Working Regex & Example Code
JavaScript
const formatCurrency = (str) => { return str.replace(/\.(?=.*\.)|\.\d+$/g, ''); }; // Test your cases console.log(formatCurrency("60.000.00")); // Output: "60000" console.log(formatCurrency("5.000.00")); // Output: "5000"
Python
import re def format_currency(s): return re.sub(r'\.(?=.*\.)|\.\d+$', '', s) // Test your cases print(format_currency("60.000.00")) # Output: 60000 print(format_currency("5.000.00")) # Output: 5000
Regex Breakdown
Let's break down /\.(?=.*\.)|\.\d+$/g to understand how it works:
\.(?=.*\.): Matches any decimal point that has another decimal point somewhere after it (these are your thousand separators). We replace these dots with an empty string, keeping the digits intact.|: Acts as an OR operator to separate the two matching patterns.\.\d+$: Targets the final decimal point and all trailing digits (the fractional part of the currency). This entire match gets replaced with an empty string to strip it out completely.- The
gflag ensures we replace all occurrences of the first pattern across the entire string.
Why Your Original Regex Didn't Work
Your regex /([\.][0-9]*?$)/g only matches the very last decimal point and any digits that follow it. That's why applying it to 60.000.00 would leave you with 60.000 instead of 60000 — it never touched the earlier thousand separator dot.
内容的提问来源于stack exchange,提问作者Riantori
相关产品推荐
相关产品推荐

