Ask a questionAsk a question
 

AnswerProblems escaping some characters

  • Thursday, November 05, 2009 10:21 PMBitFlipper Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi,

    I have an app where the user types in text into a textbox. This is used to filter the contents of a list using the RegEx class. The user can choose filter options like "Contains", "Starts With", "Ends With", etc. As far as the user is concerned, the text they type is not used as regular expressions, but just simple text (so they are not supposed to type in regular expressions themselves).

    For instance, my regular expression filter for "Contains" looks like this:

    (s){1,}

    Where "s" is the text that the user typed in, for example:

    string regexText = "(" + textBox.Text + "){1,}";

    It all works great except when the user types in some characters, like ":'. So the regex expression will be "(:){1,}". In this case it refuses to match any text that contains a ":". I tried these variations, but nothing works:

     "(:){1,}"  
     "(\\:){1,}"
     "(\\\\:){1,}"
     "(\\x3a:){1,}"
     @"((\:){1,}"
     @"((\\:){1,}"

    I also used RegEx.Escape(textBox.Text) but it doesn't do any escaping for ":".

    But nothing causes it to match anything that contains a ":". Is there a way to easily escape a whole string, so that it doesn't matter what the user types in?

    On a slightly similar note, why does the following not match "("...

     "(\\(){1,}"

    ...but...

      "(\\x28){1,}"

    ...does?

    Any ideas?

Answers

  • Thursday, November 05, 2009 10:45 PMOmegaManMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    [:]

    There are only two  or three characters one needs to escape in a character set box such as $ ^ which would be [\$\^] but every other character, such as the colon, is fair game [:=<] . So I recommend you identify all the special regex characters and where it is found put them in the character set.

    HTH
    William Wegerson (www.OmegaCoder.Com)
    • Marked As Answer byBitFlipper Friday, November 06, 2009 1:44 AM
    •  

All Replies

  • Thursday, November 05, 2009 10:45 PMOmegaManMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    [:]

    There are only two  or three characters one needs to escape in a character set box such as $ ^ which would be [\$\^] but every other character, such as the colon, is fair game [:=<] . So I recommend you identify all the special regex characters and where it is found put them in the character set.

    HTH
    William Wegerson (www.OmegaCoder.Com)
    • Marked As Answer byBitFlipper Friday, November 06, 2009 1:44 AM
    •  
  • Thursday, November 05, 2009 11:40 PMBitFlipper Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    So you are saying I should do something like this...?

    string regexText = "([" + Regex.Excape(textBox.Text) + "]){1,}";

    I will try it out.