Apply Regex.Escape() in my function that matches two strings

Viewed 82

I have a function with 3 parameters. 1st parameter might contain a wild character("*"), the 2nd parameter is a normal string, while 3rd parameter is a wild character "*". The main agenda of this function is to: Compare 1st two strings through Regex.Match() and returns:

    1. null, if 1st two strings do not match at all.
    2. Fetches and returns index from 2nd string.
    3. Returns empty if both strings match completely.

Function is as below:

static string GetIndex(string value, string stringToCompare, string wildCard)
{
                var match = Regex.Match(stringToCompare, string.Format("^{0}$", value.Replace(wildCard, @"(?<index>\d+)")), RegexOptions.IgnoreCase);
                if (match == null || !match.Success) return null;

                return match.Groups["index"].Value;
}

Function works well for:

a. var a = GetIndex("PCONND*_DHEIGHT", "PCONND2_DHEIGHT", "*"); //Result:"2"
b. var a = GetIndex("CYL1_TYPE", "CYL1_TYPE", "*"); //Result: ""

But does not work for:

a. var a = GetIndex("CTOT(1)", "CTOT(1)", "*");

I got to know, Regex.Escape() can be used to escape characters but not able to apply here so that all my above cases could be successfully validated.

2 Answers
Related