I am aware that regEx are common across languages...But I am having trouble in writing the Java syntax. I have a regular expression coded in JS as;
if((/[a-zA-Z]/).test(str) && (/[0-9]|[\x21-\x2F|\x3A-\x40|\x5B-\x60|\x7B-\x7E]/).test(str))
return true;
How do I write the same in Java ?
I have imported
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Just to add, from what I am trying it is saying \x is an invalid escape character..
You can use online regex evaluators like https://regex101.com for conversion.
ECMAScript (JavaScript) FLAVOR
TOOLS -> Code Generator (LANGUAGE - Java)
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.
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 regex languages in 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.
If you want to use the same regex in Javascript as well as Java try to get the regex string at runtime, rather than trying to define the regex at compile time. At compile time it will check for syntax and it will give you invalid escape character error, however at runtime it will not check for the syntax and will directly compile the pattern.
If you can get the regex from API or can read it from locally stored text file, it will great.
If you really need Javascript regex semantics in Java, one approach would be to use the embedded Javascript engine to evaluate the regex. For example:
Java regular expressions are first and foremost strings, so you must start with double quotes and not
/
. Also, in java, you need to escape the\
by doing two of them like so\\
.Take a look at this tutorial from Oracle for more information.
The only thing you have to do is to duplicate back slashes.