2

I am trying to achive regex expression: I need regex with email, I am using that:

\S+@\S+\.\S+

And I want to repreat it X times with ; separator. I cant figure this out... For example pattern should allow following strings:

example1@email.com
example1@email.com;example2@email.com;example3@email.com;example4@email.com

But should not allow for example following string:

example1@email.com;example2email.com;example3@email.com;
zxf18682
  • 21
  • 2

1 Answers1

1

In general, the X-separated list of entities is matched with ^y(?:Xy)*$ like pattern.

Here, there is a caveat related to what you match with y and X: \S matches ; chars, so the semi-colon has to be "removed" from the \S pattern, hence the \S should be replaced with [^\s;] in the resulting pattern.

You can use

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

See the regex demo.

Details:

  • ^ - start of string
  • [^\s;]+@[^\s;]+\.[^\s;]+ - one or more chars other than whitespace and ;, @, one or more chars other than whitespace and ;, . and then again one or more chars other than whitespace and ;
  • (?: - start of a non-capturing group:
    • ; - a semi-colon
    • [^\s;]+@[^\s;]+\.[^\s;]+ - email-like pattern (described above)
  • )* - end of the non-capturing group, repeat zero or more occurrences
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks! Generally works but now I can pass emails with strange character, for example: dasdasd+sds@wp.pl – zxf18682 Jun 10 '22 at 11:31
  • @zxf18682 In the [same way](https://regex101.com/r/Fpfqin/2). – Wiktor Stribiżew Jun 10 '22 at 11:36
  • dasdasd+sds@wp.pl should not be passed and other characters like (,),* etc. that should not contain in email – zxf18682 Jun 10 '22 at 11:58
  • @zxf18682 You need to define the rules for the user, domain and TLD parts of the regex. This is out of scope of the current question. There are a lot of email validation regex questions on SO, please use the site search. – Wiktor Stribiżew Jun 10 '22 at 12:03