2

I have a regular expression which accepts only an email with the following pattern.

@stanford.edu.uk or word.edu.word

here it is

/(\.edu\.\w\w\w?)$/

It appears that this only works when .edu is followed by ".xx" (example: school.edu.au or college.edu.uk). I need this to also work for e-mails that end with .edu (example: school.edu or student.college.edu)

I tried this:

/(\.w+\.w+\.edu)$/

If any one can help?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Saif Ali
  • 429
  • 5
  • 23

1 Answers1

1

Your (\.edu\.\w\w\w?)$ pattern requires a . and at 2 to 3 word chars after it before the end of the string, so it can't match strings with .edu at the end.

You may fix the pattern using

\.edu(?:\.\w{2,3})?$

See the regex demo

Details

  • \.edu - an .edu substring
  • (?:\.\w{2,3})? - an optional non-capturing group matching 1 or 0 occurrences of
    • \. - a dot
    • \w{2,3} - 2 to 3 word chars
  • $ - end of string.

Note that \w matches letters, digits and _. You might want to precise this bit in case you only want to match letters ([a-zA-Z] to only handle ASCII, or use ECMAScript 2018 powered \p{L} Unicode property class (not working in older browsers), or build your own pattern to support all Unicode letters).

Also, consider going through How to validate an email address using a regular expression?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563