Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  180] [ 2]  / answers: 1 / hits: 41734  / 13 Years ago, fri, january 6, 2012, 12:00:00

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


More From » java

 Answers
29

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.



[#88195] Wednesday, January 4, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allanw

Total Points: 421
Total Questions: 132
Total Answers: 102

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;