General_9
General_9

Reputation: 2319

Regex for a username?

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

Answers (1)

Tim Pietzcker
Tim Pietzcker

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:

  • for ^ that's anywhere but the first character inside the class,
  • for - it's at the start or end of the class,
  • for ] 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.

Regular expression visualization

Debuggex Demo

Upvotes: 3

Related Questions