我有一个带有货币符号的字符串。我需要只提取小数和负号。
以下是字符串和所需十进制值的一些示例:
-$ 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
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/