4

Background

I'm working on a Javascript application where users have to use a specific email domain to sign up (Either @a.com or @b.com. Anything else gets rejected).

I've created a regex string that makes sure the user doesn't do @a.com with nothing in front of it and limits users to only @a.com and @b.com. The last step is to make sure the user doesn't add extra characters to the end of @a.com by doing something like @a.com.gmail.com

This is the regex I currently have: \b[a-zA-Z0-9\.]*@(a.com|b.com)

Question

What can I use at the end to prevent anything from being added after a.com or b.com? I'm very novice at regex and have no idea where to start.

5
  • 1
    Add $ to the regex's end. $ means your match should be at the strings' end Commented Mar 16, 2016 at 20:36
  • When I do that in a regex editor online, I don't get any matches at all. Do I need to add a \ or anything? Commented Mar 16, 2016 at 20:38
  • It works for me: \b[a-zA-Z0-9\.]*@[ab]\.com$ Commented Mar 16, 2016 at 20:39
  • 1
    Ahh. I didn't have the m flag on it. Works perfectly. If you put it in an answer, I'll accept it. Thanks!! Commented Mar 16, 2016 at 20:41
  • The (m)ultiline flag threats each line as a separate string Commented Mar 16, 2016 at 20:41

1 Answer 1

6

To solve your problem add $ to the regex's end. $ means your match should be at the strings' end.

Also you can reduce (a.com|b.com) to [ab]\.com. Look I've also escaped the dot

The character class [ab] means one of its characters should be matched.

Check this demo.

As stated in the comments, be sure to use the (m)ultiline flag, this way the regex engine will threat each line as a separate string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.