货币和金额的正则表达式C#

时间:2014-10-29 09:56:11

标签: c# regex

我正在尝试为以下输出创建一个正则表达式:

Text         -                  Output Expected

$200                     currency sign = "$" and amount = 200
€ 20.34                  currency sign = "€" and amount = 20.34
£ 190,234                currency sign = "£" and amount = 190234
$  20.34                 currency sign = "$" and amount = 20.34

我对正则表达式不好,但我仍然希望用正则表达式来做这件事。任何人都可以帮我实现这个目标吗?

4 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式捕获符号和amout:

/(?<SYMBOL>[$€£]){1}\s*(?<AMOUNT>[\d.,]+)/g

DEMO(查看右侧面板上的匹配信息)

希望它有所帮助。

答案 1 :(得分:2)

您可以使用正则表达式:

(\D)\s*([.\d,]+)

caputre group 1将包含货币符号和第2组contians值

参见演示http://regex101.com/r/eV2uZ7/1

<强> EXPLANTION

(\D)计算除数字以外的任何内容

\s*匹配任意数量的空格。

[.\d,]+匹配数字,逗号和点。

更具体地说,您还可以提供\d[.\d,]*,以确保值部分始终以数字开头

答案 2 :(得分:0)

([$€£]) *([0-9.,]*)

捕获组1将是货币符号,捕获组2将是您需要删除&#34;,&#34; 之后使用替换(&#39; &#39;&#39;&#39)

答案 3 :(得分:0)

    string str = string.Empty , outPut = string.Empty;
        Regex paternWithDot = new Regex(@"\d+(\.\d+)+");
        Regex paternWithComa = new Regex(@"\d+(\,\d+)+");
        Match match = null;


        str = "& 34.34";
        if (str.Contains(".")) match = paternWithDot.Match(str);
        if (str.Contains(",")) match = paternWithComa.Match(str);
        outPut += string.Format( @" currency sign = ""{0}"" and amount = {1}" , str.Replace(match.Value, string.Empty),  match.Value) + Environment.NewLine;


        str = "€ 20.34 ";
        if (str.Contains(".")) match = paternWithDot.Match(str);
        if (str.Contains(",")) match = paternWithComa.Match(str);
        outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;

        str = "£ 190,234";
        if (str.Contains(".")) match = paternWithDot.Match(str);
        if (str.Contains(",")) match = paternWithComa.Match(str);
        outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;

        str = "$  20.34 ";
        if (str.Contains(".")) match = paternWithDot.Match(str);
        if (str.Contains(",")) match = paternWithComa.Match(str);
        outPut += string.Format(@" currency sign = ""{0}"" and amount = {1}", str.Replace(match.Value, string.Empty), match.Value) + Environment.NewLine;

        MessageBox.Show(outPut);
相关问题