【问题标题】:C#: How to extract values from a predefined format of string efficiently?C#:如何有效地从预定义格式的字符串中提取值?
【发布时间】:2011-03-15 22:35:30
【问题描述】:

我收集了类似的字符串

例如: 字符串1:客户的名字是john,姓氏是gleck,公司名称是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相反的方法,它接受引用字符串和实际字符串并返回提取的值?

【问题讨论】:

  • 你能提供一个字符串的实际例子吗?一开始,你说它看起来像一个句子,但后来你给出了一些逗号分隔的值。
  • 我相信 CSV 字符串显示了所需的输出

标签: c# .net


【解决方案1】:

正则表达式可以解决问题。

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

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

【讨论】:

  • 只要要解析的值是字符串中的最后一个单词,它就可以工作。但是如何定义像"{LastName}, {FirstName} {DateOfBirth} ({Age})" 这样的模板呢?
【解决方案2】:

(问题:您实际输入的字符串是完整的罗嗦文本:“客户的名字是xxxx,他的姓氏是xxxx,他的公司名称是xxxx”等正确吗?)

这可能是一个正则表达式的好例子。如果您使用 compile 选项,您应该可以从中获得合理的速度。本质上是您询问的“反向 string.format”(还有更多选项)。

更新:

  // NOTE: pattern assumes a comma after spending rate
  Regex regex = new Regex("Customer's first Name is (\w+), his last name is (\w+),his company name is ([\w\s]+), he has a balance of (\d+) dollars.His spending rate is ([^,]+)");

  string[] values = regex.Split(string1);  

【讨论】:

  • 詹姆斯,正则表达式似乎是要走的路。您能否分享我应该用于示例字符串 1 的正则表达式?
猜你喜欢
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
相关资源
最近更新 更多