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

如何用Python正则表达式将$、mn、bn替换为对应全称?

Python Regex Solution for Currency Notation Normalization

Got it, let's work through this currency notation normalization problem. You want to convert those shorthand $/mn/bn formats into their full-word equivalents, and cover all three variations of your input strings. Here's a solid Python regex solution that handles every case:

Step-by-Step Explanation & Code

First, we'll use a regex pattern to match all three input variations (with or without spaces between $ and the number, with or without spaces between the number and mn). Then we'll use dynamic replacement to map the abbreviations to their full names.

import re

def normalize_currency_notation(text):
    # Map shorthand abbreviations to their full-word equivalents
    abbreviation_map = {
        'mn': 'Million',
        'bn': 'Billion'
    }
    # Regex pattern breakdown:
    # - \$ : Escaped dollar sign (since $ is a special regex character)
    # - ? : Matches 0 or 1 spaces between $ and the number
    # - (\d+) : Captures the numeric value (group 1)
    # - (mn|bn) : Captures the unit abbreviation (group 2)
    pattern = r'\$ ?(\d+)(mn|bn)'
    
    # Use a lambda function to dynamically build the replacement string
    return re.sub(pattern, lambda match: f"{match.group(1)} {abbreviation_map[match.group(2)]} Dollar", text)

# Test all your input cases
test_inputs = [
    "Deal to invest $1000 mn in market.",
    "Deal to invest $1000mn in market.",
    "Deal to invest $ 1000mn in market."
]

for input_str in test_inputs:
    print(normalize_currency_notation(input_str))

Output for All Inputs

Running this code will output the same normalized string for all three inputs:

Deal to invest 1000 Million Dollar in market.

Optional Adjustment

If you prefer the grammatically correct plural form "Dollars" for amounts over 1, just update the replacement string in the lambda to:

f"{match.group(1)} {abbreviation_map[match.group(2)]} Dollars"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:34:43