我有一些相似的字符串
例如: 字符串 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/