C# 创建一个解析函数来计算字符串之间的值(成本)

C# 创建一个解析函数来计算字符串之间的值(成本),c#,C#,我想知道如何实现一个功能,使我能够计算服务成本 我的资料持有人 List<string> data = new List<string>(); data.Add("01:01 Service cost {get this value} usd."); data.Add("01:02 Service cost {get this value} usd."); data.Add("01:03 Service cost {get this value} usd."); data

我想知道如何实现一个功能,使我能够计算服务成本

我的资料持有人

List<string> data = new List<string>();
data.Add("01:01 Service cost {get this value} usd.");
data.Add("01:02 Service cost {get this value} usd.");
data.Add("01:03 Service cost {get this value} usd.");
data.Add("01:04 Service cost {get this value} usd.");
var elementMap = ParseData(data);

感谢您为实现此目标提供的提示。

您可以尝试以下方法:

 var result = data.Select(i =>
 {
     int startIndex = i.IndexOf("Service cost") + 13;
     return double.Parse(i.Substring(startIndex, i.IndexOf("usd.") - startIndex));
 }).ToList();
作为输出,我想得到总成本


您希望在正则表达式框架中使用捕获组。

Regex regMatch=new Regex(“\d\d:\d\d服务成本(?.*?)美元”)
Match result=regMatch.Match(“01:01服务成本{获取此值}美元”);
var captureGroupResult=result.Groups[“成本”];

captureGroupResult应该包含{get this value},然后把你的值加起来。

我认为在空格上拆分字符串,然后对每个数组中的第4项执行
decimal.Parse
会更容易。您能给出值的示例吗。1-999999代表实例13代表什么?字符串
string的第二个参数。Substring
是子字符串的长度,而不是结束索引。@Kavvson它是“服务成本”中的字符数加上一个。考虑使用DoC/逗号,因为你在样本中使用了特定于文化的解析。@使用的CIMEAL货币并不意味着文档的位置,也不意味着用户的习惯是如何格式化数字。这篇文章显然是由计算机生成的。公平地说,这里的值将使用严格一致的(常规!)格式,而不是用户输入的内容。。。但是OP很容易调整表情来满足他的需求。你会遇到问题的地方是,如果计算机可以生成非美元货币的数据。那么仅仅调整表达式是不够的;您还需要解析出哪种货币并连接到服务,以了解使用哪种汇率。
 var result = data.Select(i =>
 {
     int startIndex = i.IndexOf("Service cost") + 13;
     return double.Parse(i.Substring(startIndex, i.IndexOf("usd.") - startIndex));
 }).ToList();
List<string> data = new List<string>();
data.Add("01:01 Service cost {get this value} usd.");
data.Add("01:02 Service cost {get this value} usd.");
data.Add("01:03 Service cost {get this value} usd.");
data.Add("01:04 Service cost {get this value} usd.");

var exp = new Regex(@"cost ([$.0-9]+) usd.");
var result = data.Select(d => decimal.Parse(exp.Match(d).Groups[1].Value.Replace("$", ""))).Sum();
var result = data.Select(d => decimal.Parse(d.Split(" ".ToCharArray())[3].Replace("$", "")).Sum();
Regex regMatch = new Regex("\d\d:\d\d Service cost (?<cost>.*?) usd.")

Match result = regMatch.Match("01:01 Service cost {get this value} usd.");

var captureGroupResult = result.Groups["cost"];