Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
BDD Avatar asked Nov 16 '25 01:11

BDD


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!