Regular Expression is stupid, HELP!

Regular Expression is stupid, HELP!
0

#1

there is a bug : if email address is:abc.abc@gmail.com abc.abc@gmail.com.ru or abc.abc@gmail.com.cn. You cant use /[\w.]+\w+@\w+.(com|com.)/g; . It only works if you use: /[\w.]+\w+@\w+.(com.|com)/g; i dont know why i put "com." before “com” (com.|com) then it works :frowning:


#2

Try this site to learn and test regex.

http://regexr.com/


#4

i tested on that site, and dont know why put (com.|com), it’ll work. But (com|com.) its not match


#5

Huh? Neither order does what you want it to do. The reason they work differently is because the conditional logic looks for what’s before the | first, then what’s after it (think of it like if/else if.

Depends exactly how you’ll be using this, but you probably want to be searching entire strings, in which case you should start with ^ and end with $. Then you won’t have this problem, because the string either matches or it doesn’t (no partial matches allowed).

So you then might have something like this:

/^[\w.]+\w+@\w+.(com|com.(ru|cn))$/g

#6

Thank you for your great explanation, but your regex still need to be this /[\w.]+\w+@\w+.(com.(ru|cn)|com)/ in order to work


#7

Amended post above to include ^ and $.

If you want to get that to work on regexr while checking multiple strings, you also need to set the multiline tag and put each string you want to test on a different line.


#8

it still doest work :frowning:


#9

I think it shows no matches because your sample text spans multiple lines. Try adding the multiline flag.

Also, the . matches any character except a newline, so sample@yahooxcom will match. You should use \. instead (except when inside a pair of [], maybe).

Try this one:
^[\w.]+\w+@\w+\.com(\.(ru|cn))?$


#10

thanks alot for your reply, your code works !


#11

You might also want to read http://www.regular-expressions.info/email.html


#12

Good catch :slight_smile:
The dot means “anything” if it’s not escaped (and it’s greedy, so it’ll try to match as many characters as possible), only if you put . does it match a simple “dot”