通过忽略某些子串来比较两个字符串

时间:2015-09-17 14:57:01

标签: c#

我正在开发一个比较工具来比较两行是文本字符串。条件是,我需要取一个子串的一部分而忽略它以进行比较。所以例如。

两行

FILE = .test \ testfile CRC = 0x0987678 DATE = 10/09/2015 VERSION = 1

File = .test \ testfile CRC = 0x0984567 DATE = 11/09/2015 VERSION = 1

如果提供两个过滤器作为CRC和DATE,那么我需要忽略完整的字段和值。因此,CRC = 0x0987678 DATE = 10/09/2015将被忽略以进行比较,并且只会比较其余的字符串并且在上面的情况下将返回true,因为字符串的其余部分是相同的。

现在我可以通过搜索字符串,删除空格,获取值等来实现这一点,但我正在寻找一个带有正则表达式的解决方案来优化我的解决方案。谢谢。

1 个答案:

答案 0 :(得分:1)

这个问题分为两部分。首先得到参数。第二个做过滤。正则表达式是第一部分的最佳解决方案。过滤可以通过许多不同的方式完成。这是正则表达式部分。

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 = "FILE = .test\testfile CRC = 0x0987678 DATE = 10/09/2015 VERSION = 1";
            string pattern = @"(?'name'[\w]+)\s+=\s+(?'value'[^\s]+)";

            Regex expr = new Regex(pattern);
            MatchCollection matches = expr.Matches(input);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (Match match in matches)
            {
                dict.Add(match.Groups["name"].Value, match.Groups["value"].Value);
            }
        }
    }
}​