Convert Javascript regular expression to Java syntax
Change the leading and trailing '/'
characters to '"'
, and then replace each '\'
with "\\"
.
Unlike, JavaScript, Perl and other scripting languages, Java doesn't have a special syntax for regexes. Instead, they are (typically) expressed using Java string literals. But '\'
is the escape character in a Java string literal, so each '\'
in the original regex has to be escaped with a 2nd '\'
. (And if you have a literal backslash character in the regex, you end up with "\\\\"
in the Java string literal!!)
This is a bit confusing / daunting for Java novices, but it is totally logical. Just remember that you are using a Java string literal to express the regex.
However as @antak notes, there are various differences between the regex languages implemented by Java and JavaScript. So if you take an arbitrary JavaScript regex and transliterate it to Java (as above) it might not work.
Here are some references that summarize the differences.
- https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines
- https://gist.github.com/CMCDragonkai/6c933f4a7d713ef712145c5eb94a1816
You can use online regex evaluators like https://regex101.com for conversion.
- Go to https://regex101.com
- Choose
ECMAScript (JavaScript) FLAVOR
- Insert your regex
- Open
TOOLS -> Code Generator (LANGUAGE - Java)
- Copy-paste
Even though it isn't hardcore programmer way, it is significantly less error-prone. Especially if you need to convert only one or two expressions.