Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将正则表达式数组与字符串数组一起使用_C#_Arrays_Regex - Fatal编程技术网

C# 将正则表达式数组与字符串数组一起使用

C# 将正则表达式数组与字符串数组一起使用,c#,arrays,regex,C#,Arrays,Regex,我正在尝试制作一个程序,用户可以在其中输入序列号数组,并显示每个对应的产品 假设我知道产品A总是以“C02”开头,产品B总是以“X02”结尾,产品C总是包含“A1700”。然后,如果用户输入是“C02HGV32、N93XA1700D、J3429X02”,它将返回“C02HGV32:产品A;N93XA1700D:产品C;J3429X02:产品B” 如何将正则表达式数组与字符串数组进行比较?以下是我所拥有的: using System.Text.RegularExpressions; public

我正在尝试制作一个程序,用户可以在其中输入序列号数组,并显示每个对应的产品

假设我知道产品A总是以“C02”开头,产品B总是以“X02”结尾,产品C总是包含“A1700”。然后,如果用户输入是“C02HGV32、N93XA1700D、J3429X02”,它将返回“C02HGV32:产品A;N93XA1700D:产品C;J3429X02:产品B”

如何将正则表达式数组与字符串数组进行比较?以下是我所拥有的:

using System.Text.RegularExpressions;
public class ReturnProduct{
    public Regex[] compareAgainst = new Regex[3]{@"[C02]*",@"*[X02]",@"*[A1700]*"}; //Clearly not the right way, but not sure how else to do it

公共字符串getTheProduct(字符串输入){
string[]compareString=input.Split(“,”);
for(int a=0;a
正则表达式语法:

  • “^C02.*”-以C02开头,后跟任意数量的字符,包括0个字符
  • “^.*X02”-以任意数量的字符(包括0个字符)开头,以X02结尾
  • “^.A1700.*”-以任意数量的字符开头和结尾,并在某处包含A1700

    public static void GetTheProduct(string input, List<Regex> regList)
    {
        List<string> compareString = input.Split(new char[] { ',' }).ToList();
        foreach (string item in compareString)
        {
            if (regList[0].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product A");
            else if (regList[1].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product B");
            else if (regList[2].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product C");
        }
    }
    
    static void Main(string[] args)
    {
        List<Regex> regexList = new List<Regex>() { new Regex("^C02.*"), new Regex("^.*X02"), new Regex("^.*A1700.*") };
        GetTheProduct("C02HGV32,N93XA1700D,J3429X02", regexList);
        Console.ReadLine();
    }
    
    publicstaticvoid GetTheProduct(字符串输入,列表regList)
    {
    List compareString=input.Split(新字符[]{',}).ToList();
    foreach(compareString中的字符串项)
    {
    if(regList[0]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品A”);
    else if(regList[1]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品B”);
    else if(regList[2]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品C”);
    }
    }
    静态void Main(字符串[]参数)
    {
    List regexList=new List(){new Regex(^C02.*)、new Regex(^.*X02)、new Regex(^.*A1700.*);
    获取产品(“C02HGV32,N93XA1700D,J3429X02”,regexList);
    Console.ReadLine();
    }
    
您还可以推广该方法,避免硬编码产品名称。 像这样:

publicstaticvoid GetTheProduct(字符串输入,Dictionary regDictionary)
{
List compareString=input.Split(新字符[]{',}).ToList();
foreach(compareString中的字符串项)
{
string key=regDictionary.First(x=>x.Value.IsMatch(item)).key;
WriteLine(“{0}:{1}”,项,键);
}
}
静态void Main(字符串[]参数)
{
Dictionary regDictionary=新字典();
添加(“产品A”,新的正则表达式(^C02.*);
添加(“产品B”,新正则表达式(“^.*X02”);
添加(“产品C”,新的正则表达式(“^.*A1700.”);
获取产品(“C02HGV32,N93XA1700D,J3429X02”,regDictionary);
Console.ReadLine();
}
正则表达式语法:

  • “^C02.*”-以C02开头,后跟任意数量的字符,包括0个字符
  • “^.*X02”-以任意数量的字符(包括0个字符)开头,以X02结尾
  • “^.A1700.*”-以任意数量的字符开头和结尾,并在某处包含A1700

    public static void GetTheProduct(string input, List<Regex> regList)
    {
        List<string> compareString = input.Split(new char[] { ',' }).ToList();
        foreach (string item in compareString)
        {
            if (regList[0].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product A");
            else if (regList[1].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product B");
            else if (regList[2].Match(item).Success)
                Console.WriteLine("{0} : {1}", item, "Product C");
        }
    }
    
    static void Main(string[] args)
    {
        List<Regex> regexList = new List<Regex>() { new Regex("^C02.*"), new Regex("^.*X02"), new Regex("^.*A1700.*") };
        GetTheProduct("C02HGV32,N93XA1700D,J3429X02", regexList);
        Console.ReadLine();
    }
    
    publicstaticvoid GetTheProduct(字符串输入,列表regList)
    {
    List compareString=input.Split(新字符[]{',}).ToList();
    foreach(compareString中的字符串项)
    {
    if(regList[0]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品A”);
    else if(regList[1]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品B”);
    else if(regList[2]。匹配(项)。成功)
    WriteLine(“{0}:{1}”,项,“产品C”);
    }
    }
    静态void Main(字符串[]参数)
    {
    List regexList=new List(){new Regex(^C02.*)、new Regex(^.*X02)、new Regex(^.*A1700.*);
    获取产品(“C02HGV32,N93XA1700D,J3429X02”,regexList);
    Console.ReadLine();
    }
    
您还可以推广该方法,避免硬编码产品名称。 像这样:

publicstaticvoid GetTheProduct(字符串输入,Dictionary regDictionary)
{
List compareString=input.Split(新字符[]{',}).ToList();
foreach(compareString中的字符串项)
{
string key=regDictionary.First(x=>x.Value.IsMatch(item)).key;
WriteLine(“{0}:{1}”,项,键);
}
}
静态void Main(字符串[]参数)
{
Dictionary regDictionary=新字典();
添加(“产品A”,新的正则表达式(^C02.*);
添加(“产品B”,新正则表达式(“^.*X02”);
添加(“产品C”,新的正则表达式(“^.*A1700.”);
获取产品(“C02HGV32,N93XA1700D,J3429X02”,regDictionary);
Console.ReadLine();
}

为您的产品定义一个类别:

public class Product
{
    public string Name { get; set; }
    public Regex Expr { get; set; }
}
然后使用所有正则表达式创建一个数组:

var regexes = new[]
{
    new Product
    {
        Name = "Product A",
        Expr = new Regex("^C02")
    },
    new Product
    {
        Name = "Product B",
        Expr = new Regex("X02$")
    },
    new Product
    {
        Name = "Product C",
        Expr = new Regex("A1700")
    }
};
现在您可以使用
LINQ
query:

var input = "C02HGV32,N93XA1700D,J3429X02";
var result = string.Join("; ",
    input.Split(',')
    .Select(s => new {regexes.FirstOrDefault(p => p.Expr.IsMatch(s))?.Name, Value = s})
    .Select(x => $"{x.Value}: {x.Name}"));
结果将是

C02HGV32:产品A;N93XA1700D:产品C;J3429X02:产品B


为您的产品定义一个类:

public class Product
{
    public string Name { get; set; }
    public Regex Expr { get; set; }
}
然后使用所有正则表达式创建一个数组:

var regexes = new[]
{
    new Product
    {
        Name = "Product A",
        Expr = new Regex("^C02")
    },
    new Product
    {
        Name = "Product B",
        Expr = new Regex("X02$")
    },
    new Product
    {
        Name = "Product C",
        Expr = new Regex("A1700")
    }
};
现在您可以使用
LINQ
query:

var input = "C02HGV32,N93XA1700D,J3429X02";
var result = string.Join("; ",
    input.Split(',')
    .Select(s => new {regexes.FirstOrDefault(p => p.Expr.IsMatch(s))?.Name, Value = s})
    .Select(x => $"{x.Value}: {x.Name}"));
结果将是

C02HGV32:产品A;N93XA1700D:产品C;J3429X02:产品B


如果这些代码的要求非常简单,您可以使用
String.Contains
String.StartsWith
String.EndsWith
。您可以创建一个
字典
来保存产品名称和功能,以检查给定字符串是否具有产品的模式

var dict = new Dictionary<string, Predicate<string>>
{
    ["Product A"] = s => s.StartsWith("C02"),
    ["Product B"] = s => s.EndsWith("X02"),
    ["Product C"] = s => s.Contains("A1700")
};

string GetProductName(string serialNum)
{
    foreach(var keyVal in dict)
    {
        if(keyVal.Value(serialNum))
            return keyVal.Key;
    }

    return "No product name found";
}

List<(string, string)> GetProductNames(string str)
{
    var productCodes = str.Split(',');
    var productNames = new List<(string, string)>(); // list of tuples (string, string)

    foreach(var serialNum in productCodes)
    {
        productNames.Add((serialNum, GetProductName(serialNum)));
    }

    return productNames;
}
var dict=新字典
{
[“产品A”]=s=>s.StartsWith(“C02”),
[“产品B”]=s=>s.EndsWith(“X02”),
[“产品C”]=s=>s.Contains(“A1700”)
};
字符串GetProductName(字符串serialNum)
{
foreach(dict中的var keyVal)
{
if(keyVal.Value(serialNum))
返回keyVal.Key;
}
返回“未找到产品名称”;
}
列出GetProductNames(字符串str)
{
var productCodes=str.Split(',');
var PRODUCTNAME=new