如何调整字符串中货币符号相对于数字的位置?
调整字符串中$符号至数字前方的解决方案
要实现将数字后的$移至数字前方的需求,最简洁的方式是用正则表达式匹配替换,精准定位"数字+$"的模式并调换位置。
核心思路
匹配所有「整数/带小数的数字」紧跟$的片段,将捕获到的数字部分前置$符号。
代码示例
Python 实现
import re input_str = "the price is 18$. It increased to 24.50$ ." output_str = re.sub(r'(\d+(?:\.\d+)?)\$', r'$\1', input_str) print(output_str) # 输出: the price is $18. It increased to $24.50 .
C# 实现
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "the price is 18$. It increased to 24.50$ ."; string output = Regex.Replace(input, @"(\d+(?:\.\d+)?)\$", @"$$$1"); Console.WriteLine(output); // 输出: the price is $18. It increased to $24.50 . } }
正则表达式说明
(\d+(?:\.\d+)?):捕获组,匹配合法数字格式:\d+:匹配1个及以上的数字(整数部分)(?:\.\d+)?:非捕获组,匹配可选的小数部分(.+1个及以上数字),?表示该部分可省略
\$:匹配字面意义的$(正则中$是特殊字符,需转义)
扩展适配
如果需要支持带千分位的数字(如1,234$),可将正则调整为:
(\d{1,3}(?:,\d{3})*(?:\.\d+)?)\\$
内容的提问来源于stack exchange,提问作者DarkWarrior
相关产品推荐
相关产品推荐

