C#:如何有效地从预定义格式的字符串中提取值?

标签 c# .net

我有一些相似的字符串

例如: 字符串 1:客户的名字是 john,他的姓是 glueck,他的公司名称是 abc def technolgies llc,他有 60 美元的余额。他的支出率为 +3.45%

字符串2:客户的名字是steve,他的姓是johnston,他的公司名称是xyz corporation,他有800美元的余额。他的消费率为-212.86%

现在我必须从字符串 1 中提取 john,glueck,abc def technolgies llc,60,+3.45 和从字符串 2 中提取 steve,johnston,xyz corporation,800,-212.86 等值。

在我们的生产环境中,每个字符串都非常大,我有大约 83 个字段要从每个字符串中提取。提取这些值的最佳方法是什么?

是否有任何方法与 string.format 相反,它采用引用字符串和实际字符串并返回提取的值?

最佳答案

正则表达式就可以了。

namespace ConsoleApplication
{
    using System;
    using System.Text.RegularExpressions;

    internal static class Program
    {
        private static void Main()
        {
            var expression = new Regex(
                @"Customer's first Name is (?<FirstName>[^,]+), " +
                @"his last name is (?<LastName>[^,]+), " +
                @"his company name is (?<CompanyName>[^,]+), " +
                @"he has a balance of (?<Balance>[0-9]+) dollars\. " +
                @"His spending rate is (?<SpendingRate>[^%]+)%");

            var line = @"Customer's first Name is john, his last name is glueck, his company name is abc def technolgies llc, he has a balance of 60 dollars. His spending rate is +3.45%";

            var match = expression.Match(line);

            Console.WriteLine("First name......{0}", match.Groups["FirstName"]);
            Console.WriteLine("Last name.......{0}", match.Groups["LastName"]);
            Console.WriteLine("Balance.........{0}", match.Groups["Balance"]);
            Console.WriteLine("Spending rate...{0}", match.Groups["SpendingRate"]);

            Console.ReadLine();
        }
    }
}

输出

First name......john
Last name.......glueck
Balance.........60
Spending rate...+3.45

之后,您可以执行一些简单的字符串解析以从字符串中获取数值。此外,如果输入格式存在一些变化,您可能必须编写更健壮的正则表达式。

关于C#:如何有效地从预定义格式的字符串中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3247867/

相关文章:

c# - HttpClient 通过 BSON 到 RESTful API

c# - Twilio Rest API 抛出错误 : Could not load type 'Twilio.TwilioClient' from assembly 'Twilio, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

c# - Xamarin Android 渲染器中的长触手势

c# - GUID 比较中的性能

c# - LINQ2SQL中如何获取Context.SubmitChanges生成的SQL?

c# - 如何在2个Windows服务之间形成依赖关系

c# - AutoMapper DynamicMap 对象与匿名类型

c# - 如何将 XML 集合反序列化为 .NET 中的字典?

c# - 在 C# 中确定操作系统和处理器类型

.net - 错误解析引用