货币和金额C#的Regex

本文关键字:Regex 金额 货币 | 更新日期: 2023-09-27 18:28:25

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

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

我不擅长使用regex,但我仍然想使用regex。有人能帮我做到这一点吗?

货币和金额C#的Regex

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

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

DEMO(查看右侧面板上的比赛信息)

希望能有所帮助。

您可以使用regex:

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

caputre组1将包含货币符号,组2包含值

查看演示http://regex101.com/r/eV2uZ7/1

解释

('D)计算数字以外的任何东西

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

[.'d,]+匹配数字、逗号和句点。

更具体地说,您还可以给出'd[.'d,]*,它确保值部分始终以数字开头

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

捕获组1将是货币符号,捕获组2将是您还需要删除的金额","之后用Replace(',',')

    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);