Reputation: 2319
In C#, I am trying to validate a username with the following restrictions:
The username has no restrictions on what character it can start with, all of the above are acceptable. Can you help me come up with this regex, especially the characters I would have to escape because they already mean something in Regex rules?
Upvotes: 2
Views: 334
Reputation: 336478
In a character class, you just need to look out for ^
, -
, ]
and \
.
The first three must be escaped or placed in unambiguous positions:
^
that's anywhere but the first character inside the class, -
it's at the start or end of the class,]
it's at the start of the class (this is possible at least in .NET but not in JavaScript, for example).The backslash must always be escaped.
So this works:
^[]A-Za-z0-9!#$%&'*+/=?^_`{|}~\\,.@()<>[-]*$
but I would use
^[A-Za-z0-9!#$%&'*+/=?^_`{|}~\\,.@()<>[\]-]*$
for portability.
Upvotes: 3