Search code examples
c#regexspecial-characters

C# Regex to detect usage of Special characters


I want to filter out special characters in C#. Basically i want to allow A-Z, a-z, 0-9, hyphen, underscore, (, ), commas, spaces, \, /, spaces. Everything else is not allowed.

I have come up with the following regex ->

[a-zA-Z0-9-\b/(),_\s]*

but this doesn't seem to work fine.

Am I missing something?


Solution

  • If you want to filter out characters that don't match those, use a ^ at the beginning of the character class:

    [^a-zA-Z0-9\-\\/(),_\s]+
    

    The + quantifier will match any chars not in the character class at least once. Also, hyphens are meta characters inside character classes, so you should escape the dangling one you have, as I have done in my example. Also, if you want to include \ as an allowed character, you also need to escape it inside a character class, like [\\].

    Also, inside a character class (also known as a character set defined by [ ]), \b is a backspace character, not a word boundary.