Matt
Matt

Reputation: 3848

comma separated regex

I have an email regex I am happy with, lets call it EMAIL. So my field validator looks like this

var regex=/^EMAIL$/

But now the Captain tells me he wants to allow comma separated emails in the field.

What first comes to mind is something like

/^(EMAIL)?(, EMAIL)*$/

but that repeats EMAIL, which already offends my senses. Is there a way to write this regex without repeating EMAIL?

Upvotes: 1

Views: 403

Answers (4)

sdleihssirhc
sdleihssirhc

Reputation: 42496

Jason's seems the simplest, but for what it's worth, you could also use backreferences: ^EMAIL, EMAIL$ would be the same as ^(EMAIL), \1$.

Upvotes: 1

Jason
Jason

Reputation: 10912

This covers all the examples mentioned

^(EMAIL(,\s|$))+$

It matches

EMAIL
EMAIL, EMAIL

but not

EMAILEMAIL

Upvotes: 3

dheerosaur
dheerosaur

Reputation: 15172

I can't think of a way to match email list as it is, without repeating EMAIL. Here is a simple workaround:

/^(EMAIL, )+$/.test(emailList + ", ");

Example:

var s = "abc, def, ghi, jkl";
/^([a-z]+, )+$/.test(s + ", ");

Upvotes: 2

cjk
cjk

Reputation: 46475

Split the value by comma, then use the regex on each one.

Upvotes: 3

Related Questions