Search code examples
c#regexif-statementexpressioncharacter-class

C# Regex Character Class / String Pattern - to identify exclamation mark


I want to do something like this --- if an expression contains exclamation mark, error; else, no error.

The expression may be a value itself or math/string function. Example as below:
expr = abc;
expr = 123;
expr = concatenate(123,abc);
expr = sin(0.5);

I'm using Regex library to identify the string pattern.
For every of the expression above, they didn't prompt out error (expected result), except for the last expression "expr=sin(0.5)", it prompts out error! Which it supposingly not to do so.

So just wonder if I've written the string pattern wrongly? Or which part of the code that I need to modify in order to get the correct result?

Provided with my code:

if (Regex.IsMatch(_exprWithVariableValues, @"[.*!+.*]+"))
    _result = "Invalid value";
else
    _result = "Correct";

Solution

  • This is much too simple for regular expressions. Your regular expression literally needs to be this:

    !
    

    ..or just check it with C#:

    if (_exprWithVariableValues.IndexOf("!") > -1) {
        // invalid
    }
    else {
        // valid
    }