Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java Regex to javascript regex

([a-zA-Z0-9_\\-])([a-zA-Z0-9_\\.+~!#/$%^&*_=\\'?\\-]*)@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z0-9]{2,})$

which is working fine for Java but it is not working for JavaScript might be backward slash have a some problem, please tell me how I can convert above java regex into Java Script.

like image 988
Apurv Jain Avatar asked Apr 03 '14 05:04

Apurv Jain


People also ask

Is regex in JavaScript same as Java?

Your regex works just as well in JavaScript as Java.

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

How do you make a regular expression safe in Java?

Get rid of "/" and "/g" at the start and the end of regex. Then you need to escape every "\" occurrence like so: "\\" . The "g" part means global. This is controlled in how you use regex in Java as opposed to in the regex string.


2 Answers

Just reduce the double backslashes to singles. Also, you don't need to escape hyphen if it's the last character in a character class. Also also, you don't need to escape wildcard characters in a character class

Something like this

/([a-zA-Z0-9_-])([a-zA-Z0-9_.+~!#/$%^&*_='?-]*)@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z0-9]{2,})$/
like image 192
Phil Avatar answered Oct 20 '22 09:10

Phil


It depends on how you are using this? In what code?

you probably just need one \ everywhere you have two \\.

var re = new RegExp("ab+c");

or

var re = /ab+c/;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

like image 21
DrLivingston Avatar answered Oct 20 '22 10:10

DrLivingston