Regex which matches all alpha numeric chars and zero or one '@' symbol

Viewed 69

I need a regex which matches all alpha numeric chars and zero or one '@' symbol in any part of the string, so:-

Ab01@ - match
Ab0@1 - match
@Ab01 - match

here's what I have:-

/^[A-Za-z0-9]+@{0,1}$/

The above matches the '@' when it's at the end of the string but doesn't match when it's at the start or in the middle, for example

@Ab01 - no match
Ab@01 - no match

I've tried removing the ^ & $ indicating start and end of the expression - but this allows more than one match of the @ which is not what I want.

2 Answers

If the @ can be there only a single time, you can match optional chars from [A-Za-z0-9] and optionally match an @ in between.

If you don't want to match empty strings and a negative lookahead is supported:

^(?!$)[A-Za-z0-9]*@?[A-Za-z0-9]*$

Regex demo

If there has to be at least a single char of [A-Za-z0-9] present, you could also use

^(?=@?[A-Za-z0-9])[A-Za-z0-9]*@?[A-Za-z0-9]*$

Regex demo

Alternatively maybe use:

^(?!.*@.*@)[A-Za-z\d@]+$

See the demo.


  • ^ - Start string ancor.
  • (?!.*@.*@) - Negative lookahead to prevent multiple "@".
  • [A-Za-z\d@]+ - One or more characters from the specified character class.
  • $ - End string ancor.
Related