BDD
BDD

Reputation: 715

How can I prevent extra characters at the end of my string in Regex?

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.

Upvotes: 3

Views: 1553

Answers (1)

user4227915
user4227915

Reputation:

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.

Upvotes: 5

Related Questions