Convert Javascript regular expression to Java synt

2020-01-30 06:32发布

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

6条回答
甜甜的少女心
2楼-- · 2020-01-30 06:54

You can use online regex evaluators like https://regex101.com for conversion.

  1. Go to https://regex101.com
  2. Choose ECMAScript (JavaScript) FLAVOR
  3. Insert your regex
  4. Open TOOLS -> Code Generator (LANGUAGE - Java)
  5. 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.

查看更多
Rolldiameter
3楼-- · 2020-01-30 06:55

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.

查看更多
Evening l夕情丶
4楼-- · 2020-01-30 06:56

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.

查看更多
闹够了就滚
5楼-- · 2020-01-30 07:05

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:

javax.script.ScriptEngineManager se = new javax.script.ScriptEngineManager();
javax.script.ScriptEngine engine = se.getEngineByName("js");

String regExp = "/^\\d+$/";
engine.put("str", "1234");
engine.eval("var rgx=" + regExp);
Object value = engine.eval(
    "function validate(r, s){ return (r).test(s);};validate(rgx, str);");
logger.log(value);
查看更多
Deceive 欺骗
6楼-- · 2020-01-30 07:05

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.

查看更多
▲ chillily
7楼-- · 2020-01-30 07:14

The only thing you have to do is to duplicate back slashes.

Pattern p1 = Pattern.compile("[a-zA-Z]");
Pattern p2 = Pattern.compile("[0-9]|[\\x21-\\x2F|\\x3A-\\x40|\\x5B-\\x60|\\x7B-\\x7E]");

if (p1.matcher(str).find() && p2.matcher(str).find()) {
    return true;
}
查看更多
登录 后发表回答