user3106666
user3106666

Reputation: 41

Compare two strings by ignoring certain substrings

I am developing a comparison tool to compare two lines which are text strings.The condition is that,i will need to take a certain part of the substring and ignore it for comparison.So for e.g.

two lines

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

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

if two filters are provided as CRC and DATE,then i need to ignore the complete field and value.so CRC = 0x0987678 DATE = 10/09/2015 will be ignored for comparison and only rest of the string will be compared and in above case will return true,as the rest of the string is same.

Now i can do this by searching string,removing white spaces,getting the value etc but i am looking for a solution with regular expressions to optimize my solutions.Thanks.

Upvotes: 1

Views: 1811

Answers (1)

jdweng
jdweng

Reputation: 34421

There are two parts to this question. First to get the parameters. Second to do the filtering. Regex is the best solution to the first part. The filtering can be done lots of different ways. Here is the regex part.

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

Upvotes: 1

Related Questions