Nutella said:
Hi all,
I need to validate a string in C-sharp using the Regex class.
The rules are:
-can only contain alpha-numeric characters, '_' or '-'
-Nothing else, no spaces, no funny characters.
e.g. "HELLO_WORLD-1234_abc-ABC"
What's the Regex pattern for this??
If the string may be empty:
^[\w\-]*$
If the string has to contain at least one character:
^[\w\-]+$
^ matches the beginning of the string
$ matches the end of the string
[] is a characrer set matching one character
\w matches A-Z, a-z, 0-9 or _
\- matches the character -
* is a quantifier for zero or more times
+ is a quantifier for one or more times
The escaping backslash before the dash in the set may not be needed,
but a dash has a special meaning inside a character set, and it's
clearer both for the Regex object and for the person reading the code
that it's the character - that is intended. If you later on add more
characters, you could easily forget that it needed escaping:
Adding some characters: ^[\w#!-]+$
Adding some more characters: ^[\w#!-&%]+$
Oops, now you have the span ! to & instead of the three separate
characters...