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

正则表达式需求:移除货币格式中的小数点及小数部分

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 g flag 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:33:22