正则表达式替换字符串中的现金值

时间:2015-07-18 21:58:07

标签: c# regex

我正在尝试使用正则表达式替换句子中的现金值,到目前为止我正在使用此正则表达式[+-]?\$\s?((\d{1,3},?)+.?\d{2}?)\b

以下是我提出的测试用例,其中test是应该捕获和替换的案例,ntest是正数。

public static void Main(string[] args)
{
    string test = "$500, $5,000.00  $50.00   $.99  $80 -$500 $90!";
    string output = Regex.Replace(test, @"[+-]?\$\s?((\d{1,3},?)+.?\d{2}?)\b", "money");
    Console.WriteLine(output);

    string ntest = "a$500, 00$5,000.00  $50.$00   $.99.00.00  $80.0000 --$90.00  !$90 ";
    string output2 = Regex.Replace(ntest, @"[+-]?\$\s?((\d{1,3},?)+.?\d{2}?)\b", "money");
    Console.WriteLine(output2);

}

到目前为止,它捕获了大多数测试用例,但我无法定义边界。结果:

money, money  money   $.99  $80 money $90!
amoneymoney  $50.$00   $.99.00.00  $80.0000 -money  !$90 

结果应该看起来像:

money, money  money   money  money money money!
a$500, 00$5,000.00  $50.$00   $.99.00.00  $80.0000 --$90.00  !$90  

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找这个正则表达式:

(?<=\s|^)\B[+-]?\$\s?\d{0,3}(?:,?\d{3})*(?:\.?\d{2})?\b(?=(?!\.)\p{P}|\s|$)

(或者,相当于:(?<=\s|^)\B[+-]?\$\s?\d{0,3}(?:,?\d{3})*(?:\.?\d{2})?\b(?=[\p{P}-[.]]|\s|$)

请参阅demo

enter image description here

答案 1 :(得分:0)

不确定你到底在寻找什么,但你可以尝试这样的事情:

(?<=\s|\A)\B[+-]?\$\d{0,3}(?:,\d{3})*(?:\.\d{2})?\b(?=\s|\p{P}(?![\d$])|\z)