need help in regular expression

I'm building a search and replace tool. I'm searching for strings in the correct case so I'm using regular expression (unless there are other string functions that can handle search in the correct casing, is there any ). But in my regex my problem is if the search string has special characters like [.\^$], etc. How do I make sure that my string is being evaluated by the regex as literal

Here's my method:

private static bool StringContains(string line, string searchString, bool matchCase)

{

//problem here with regex, what i wanted is to search for the literal string searchString

//if searchString has special characters like . \ ^ $, it will use this in the regex

//so if my search string is ".css" this will match any string that has 4 or more characters

//that ends with css, not necessarily a ".css", i want it to match only the literal ".css".

Match m = Regex.Match(line, searchString);

Match mi = Regex.Match(line, searchString, RegexOptions.IgnoreCase);

if (matchCase)

{

if (m.Success)

return true;

}

else if (mi.Success)

{

return true;

}

return false;

}



Answer this question

need help in regular expression

  • Murre

    OK, i found the solution. There is a support function called: Regex.Escape(string), that will do this. So all I have to do is:

    Match m = Regex.Match(line, Regex.Escape(searchString));


  • omrivm

    It might be unadvisable to use a Regex in your case... in VS2005 there is the following alternative:

    private static bool StringContains (string line, string searchString) { // I skipped ignoreCase as you don't seem to use it
    return (line.IndexOf (string, StringComparison.CurrentCultureIgnoreCase) > -1);
    }

    HTH
    --mc


  • need help in regular expression