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

本文关键字:字符串 比较 两个 | 更新日期: 2023-09-27 18:13:14

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

两行

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,因为字符串的其余部分是相同的。

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

这个问题有两个部分。首先得到参数。其次要做过滤。Regex是第一部分的最佳解决方案。过滤可以有很多不同的方式。这是正则表达式部分。

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);
            }
        }
    }
}​

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