C# 在多行字符串中搜索关键字和存储变量

C# Search multiline string for keyword and store variables

我有一个从数据库中获取的多行字符串。 该字符串的格式如下:

The below text is for the label program

COMPANY=ComanyName
PRODUCT=ProductName
SERIALMASK=123456789YYWWXXXX

如何浏览此文本并使用 ComanyName, ProductName, 123456789YYWWXXXX 存储变量或数组,以便将这些值插入 Windows Forms Application 上的文本框?

我最大的障碍是有时格式是:

The below text is for the label program

Company1 Information: 
COMPANY=ComanyName 
PRODUCT=ProductName 
SERIALMASK=123456789YYWWXXXX

Company2 Information: 
COMPANY=ComanyName 
PRODUCT=ProductName 
SERIALMASK=123456789YYWWXXXX

在那种情况下,我只想提取第一次出现的 COMPANYPRODUCTSERIALMASK 变量。

现在我有了将每一行保存在变量中的代码,我想我可以 运行 在 foreach 循环中使用 switch-case 函数并查找子字符串。但我希望有更有效的方法

试试下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "COMPANY=ComanyName\n" +
                "PRODUCT=ProductName\n" +
                "SERIALMASK=123456789YYWWXXXX\n";

            string pattern = @"(?'name'\w+)=(?'value'\w+)";

            MatchCollection matches = Regex.Matches(input,pattern);

            foreach(Match match in matches)
            {
                Console.WriteLine("Name : '{0}', Value : '{1}'", match.Groups["name"].Value, match.Groups["value"].Value);
            }
            Console.ReadLine();

            Dictionary<string, string> dict = matches.Cast<Match>()
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}

这可能对你有用

string allText = File.ReadAllText("JsonFound.txt");
List<string> allrecord = allText.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries)
                                .Where(x => x.Contains(":"))
                                .ToList();
List<CompanyInfo> CompanyInfos = new List<CompanyInfo>();
List<string> infos = new List<string>();
foreach(string s in allrecord)
{
    infos = s.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
             .Skip(Math.Max(0, 1))
                       .SelectMany(q=>q.Split('='))
             .ToList();

    CompanyInfo ci = new CompanyInfo();
    ci.CompanyName = infos[1];
    ci.ProductName = infos[3];
    ci.SerialMaskNumber = infos[5];
    CompanyInfos.Add(ci);
}

Class CompanyInfo 看起来像这样

public class CompanyInfo
{
    public string CompanyName
    {
        get;
        set;
    }
    public string ProductName
    {
        get;
        set;
    }
    public string SerialMaskNumber
    {
        get;
        set;
    }
}

你可以使用HashSet函数。该列表不包含重复记录。

var hashSet = new HashSet<CompanyInfo>(CompanyInfos);