c# - 从货币字符串中获取负小数

标签 c# regex

我有一个带有货币符号的字符串。我需要只提取小数和负号。

以下是字符串和所需十进制值的一些示例:

-$ 100 : -100 
C$ 400.68 : 400.68
-$ 578.89: -578.89

这是我当前正在使用的代码。

        var match = Regex.Match(valueToParse, @"-?[0-9]*\.?[0-9]+");
        if (match.Success)
        {
            decimal.TryParse(match.Value, out result);
        }

它适用于提取十进制数字,但不适用于第一个和第三个示例。如有任何建议,我们将不胜感激。

最佳答案

您可以使用此正则表达式替换除 -、数字和 之外的所有内容。 将此正则表达式与空字符串一起使用,

[^-\d\n.]+

这只会留下你想要的带有负号的数字。

<强> Demo

C# Demo

Regex regex = new Regex(@"[^-\d\n.]+");
string input = "-$ 100";
string result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);
input = "C$ 400.68";
result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);
input = "-$ 578.89";
result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);

打印,

-$ 100 --> -100
C$ 400.68 --> 400.68
-$ 578.89 --> -578.89

关于c# - 从货币字符串中获取负小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616369/

相关文章:

c# - 在 Atom 上网本上使用 WPF 的高 CPU

c# - 在没有大量新调用的情况下转换结构的 C++ 数组?

c# - System.Reflection - 如何调用子级别类型的 getter 方法?

regex - 仅当第二列中的内容为正数时才返回输出的所有列

javascript - 正则表达式替换字符串中的函数

c# - 如何从其 Win32 句柄中获取 System.Windows.Form 实例?

c# 一对多字符串解析帮助使用正则表达式 lambda

ios - RegExp 结果不是我的预期

java - 正则表达式忽略某些模式

ruby - 如何在 Ruby 中保留 float 的同时拆分包含算术表达式的字符串