1

I am trying to match a regex for an email address with the following conditions.

  • String must not contain more than 40 characters.
  • String matches the format emailid@domain where both emailid and domain contains only lowercase English letters, digits, and period(.)
  • domain should contain at least one period(.)
  • both email id and domain must not contain any consecutive period (.)

So Far, I am able to fulfill only the second condition with this regex:

/^[a-z0-9.]+@[a-z0-9.-]+\.[a-zA-Z]{2,6}$/

Any idea, how can I complete the other conditions?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Devilism
  • 147
  • 2
  • 5
  • 20

2 Answers2

2

You can use a single negative lookahead to make sure that the string does not contain 41 characters.

If you repeat the character class without a period 1 or more times, followed by optionally repeating a group that starts with a period, you prevent matching consecutive periods.

This part \.[a-zA-Z]{2,6}$ already makes sure that there is at least a single period.

^(?!.{41})[a-z0-9]+(?:\.[a-z0-9]+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-zA-Z]{2,6}$

Regex demo

Note that because the - is still in this character class [a-z0-9-]+, consecutive hyphens are still possible. If you don't want to allow this, you can use

^(?!.{41})[a-z0-9]+(?:\.[a-z0-9]+)*@[a-z0-9]+(?:[.-][a-z0-9-]+)*\.[a-zA-Z]{2,6}$
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Use positive lookahead:

/(?=^[a-z0-9.]+@[a-z0-9.-]+\.[a-zA-Z]{2,6}$)(?=^.{1,40}$)/

reference: https://stackoverflow.com/a/469951/1031191 by Jason Cohen:

"(?=match this expression)(?=match this too)(?=oh, and this)"

tested on: https://regex101.com/

Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91