MojoDK
MojoDK

Reputation: 4528

Regex: How to accept at-sign (@)?

I try to use this regex:

^[a-z0-9_-@]{3,15}$ 

... but it throws an exception due to the @ sign. How can I make it accept the @ sign?

Upvotes: 1

Views: 535

Answers (2)

falsetru
falsetru

Reputation: 369274

Escape -, Or move it to the beginning of the character class ([]):

@"^[a-z0-9_\-@]{3,15}$"

@"^[-a-z0-9_@]{3,15}$"

Without escaping [.. _-@] try to match characters between _ and @. But there's no charcter between them: Because ASCII code of _ and @ is 95, 64. The error message address this. (Even though it match characters between @ and _, it may not be what you want.)

C# example

Reference: Error message (mono)

Unhandled Exception: System.ArgumentException: parsing "^[a-z0-9_-@]{3,15}$" - [95-64] range in reverse order.
Parameter name: ^[a-z0-9_-@]{3,15}$
  at System.Text.RegularExpressions.Syntax.Parser.ParseCharacterClass (RegexOptions options) [0x00000] in <filename unknown>:0 
  ...

Upvotes: 5

gwillie
gwillie

Reputation: 1899

Move the - hyphen to the end of the regex like so:

^[a-z0-9_@-]{3,15}$

Upvotes: 2

Related Questions