Search code examples
c#regexstringescapingverbatim-string

C# regex does not allow special characters correctly?


For example I have the following string:

thats a\n\ntest\nwith multiline \n\nthings...

I tried to use the following code which does not work correctly and still hasn't all chars included:

string text = "thats a\n\ntest\nwith multiline \n\nthings and so on";
var res = Regex.IsMatch(text, @"^([a-zA-Z0-9äöüÄÖÜß\-|()[\]/%'<>_?!=,*. ':;#+\\])+$");
Console.WriteLine(res);

I want the regex returning true when only the following chars are included (do not have to contain all of them but at least one of the following and no others): a-z, A-Z, 0-9, äüöÄÖÜß and !#'-.:,; ^"§$%&/()=?\}][{³²°*+~'_<>|.

This is a list of known keyboard characters I thought of would be nice the use inside of a message.


Solution

  • If you specified all the chars you want to allow, the regex declaration in C# will look like

    @"^[a-zA-Z0-9äüöÄÖÜß!#'\-.:,; ^""§$%&/()=?\\}\][{³²°*+~'_<>|]+$"
    

    However, the test string you supplied contains line feed (LF, \n, \x0A) chars, so you need to either test on a string with no newlines, or add \n to the character class:

    @"^[a-zA-Z0-9äüöÄÖÜß!#'\-.:,; ^""§$%&/()=?\\}\][{³²°*+~'_<>|\n]+$"
    

    Note that the " char is doubled since this is the only way to put a double quote into a verbatim string literal.

    Also, the capturing parentheses in your pattern create redundant overhead, you should remove them.