Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript regular expression to Java syntax

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..

like image 566
copenndthagen Avatar asked Jan 06 '12 06:01

copenndthagen


People also ask

Is JavaScript regex same as Java?

There is a difference between Java and JavaScript regex flavors: JS does not support lookbehind. A tabulation of differences between regex flavors can be found on Wikipedia. However, this does not apply to your case.

What is regex \\ s in Java?

The Java regex pattern \\s+ is used to match multiple whitespace characters when applying a regex search to your specified value. The pattern is a modified version of \\s which is used to match a single whitespace character. The difference is easy to see with an example.

How do you replace a regular expression in a string in Java?

replaceAll() The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.


1 Answers

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
like image 154
Stephen C Avatar answered Sep 23 '22 12:09

Stephen C