# Monday, June 01, 2009

Checking a string for illegal characters using Regular Expressions

In our Maine Microsoft Certification Study Group we recently had a discussion about using regular expression. Today I found myself writing a RegEx to check for illegal characters in a formula (string). I thought I’d share the solution:

private bool FormulaContainsIllegalCharacters( string formula )

{

    bool result = false;

    try

    {

        Regex r = new Regex( @"(!)|(@)|(#)|(\$)|(%)|(&)" );

        result = r.Match( formula ).Success;

    }

    catch { } // ignore any regular expressions errors -> return false

    return result;

}

In my case I’m not interested in handling exceptions. If a technical error occurs I will accept the input. Notice that I needed to put a “\” before the $ sign, since the $ is a reserved character marking the end of a line.
I don’t need to put each character in “( )” brackets, but for personal preference I just find it easer to read.

#    Comments [0] |
Comments are closed.