[英]Get decimal value from string using regex C#
我想提取输入字符串的十进制值
"Total (pre tax) 93.78 EUR"
我尝试过
Regex.Replace(string input, "[^0-9]+", string.Empty)
但仅提取了“ 9370” ,预期结果为“ 97.30” 。
请帮助我获取该模式以获取十进制值 。
我建议匹配而不是替换 :让我们提取感兴趣的值,而不是删除所有其他字符。
string result = Regex.Match(
"Total (pre tax) 93.78 EUR",
@"[0-9]+(\.[0-9]+)?")
.Value;
您目前正在替换的不是数字的所有内容,包括.
。
我建议您使用可选的“点后跟更多数字”来捕获数字组。 这样,您还可以从文本中捕获多个值-或根据需要根据任何条件拒绝它。 这是一个例子:
using System;
using System.Text.RegularExpressions;
class Program
{
public static void Main()
{
string text = "I start with 5 and take away 2.52 to get 2.48 as a result";
Regex regex = new Regex(@"\d+(\.\d+)?");
var matches = regex.Matches(text);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
输出:
5
2.52
2.48
您可以使用MatchCollection.Count
来确定有多少个匹配项-我们不知道您的上下文,但是您可能希望根据是否存在匹配项,恰好是一个匹配项或不止一个匹配项来采取不同的操作。
对于整数或浮点数:
string result = Regex.Match(input,@"[0-9]+(\.[0-9]+)?").Value;
仅用于浮点数:
string result = Regex.Match(input,@"[0-9]+\.[0-9]+").Value;
如果添加'.'
则可以将其用作快速技巧'.'
到要保留的字符列表,即[^0-9.]
。 但是,这将不够健壮,因为它将保留其他数字,例如
Total (inclusive of 20% VAT) 93.78 EUR
会产生2093.78
,这不是您想要的。
更好的方法是使用特定于价格的正则表达式,例如
@"(\d+[.,]\d\d) EUR"
当后面跟EUR
时,将匹配一个带有两位十进制数字的数字。
Regex.Split()
将从输入字符串中提取所有浮动值,并将其存储到string[]
,就像string.Split
函数一样简单
您可以尝试以下操作:
string stringInput = "Total (pre tax) 93.78 EUR";
string[] splitValue = Regex.Split (stringInput , @"[^0-9\.]+");
foreach(string item in splitValue)
{
//Here you can convert it to decimal
Console.WriteLine(item);
}
输出:
93.78
string input = "Java JDK 12.0.1";
var result = Regex.Matches(input, @"[0-9]+(\.[0-9]\.[0-9]+)?");
结果:12.0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.