2015-07-18 23 views
1

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

这里是我想出的测试用例,其中test是应该被捕获和替换的案例,而ntest是fals肯定的。

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

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

(?<=\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

+0

接近,但你拍摄的逗号和感叹号 – ccsv

+0

我忘了另外两个案例$ 1000000及$ 100000.00台 – ccsv

+0

刚才的逗号可选。 –

0

不知道你是否完全寻找,但你可以尝试这样的事:

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