ObiGonz
ObiGonz

Reputation: 33

Regex for email (shouldn't match string after ; )

I have the following regex: /(\s?[^\s,]+@[^\s,]+.[^\s,]+\s?;)*(\s?[^\s,]+@[^\s,]+.[^\s,]+)/g

Could you tell me why it matches this string: "[email protected];tesr" and doesn't match this one: "[email protected]; test" ?

It shouldn't match the first string. However if there is a valid email after the ; like [email protected], it should be matched.

I will be very grateful if you could help me out.

Upvotes: 1

Views: 78

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

You can use

^[^@\s;]+@[^\s;]+\.[^\s;]+(?:\s*;\s*[^@\s;]+@[^\s;]+\.[^\s;]+)*;?$

See the regex demo. Details:

  • ^ - start of string
  • [^@\s;]+ - zero or more chars other than @, whitespace and ;
  • @ - a @ char
  • [^\s;]+ - zero or more chars other than whitespace and ;
  • \. - a dot
  • [^\s;]+ - zero or more chars other than whitespace and ;
  • (?:\s*;\s*[^@\s;]+@[^\s;]+\.[^\s;]+)* - zero or more repetition of a ; enclosed with zero or more whitespaces, and then the same pattern as above
  • ;? - an optional ;
  • $ - end of string.

Upvotes: 1

Related Questions