How to convert javascript regex to safe java-regex?

strOutput.replace("/{{[^]*?}}/g",""); 

Is there a way to convert JavaScript regular expressions to Java safe regular expressions?

The above statement gives me an error:

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

I am not so familiar with regex, so I could use some guidelines.

Thanks!

+6
java javascript regex
source share
3 answers

Get rid of the slash. You do not need those in Java. In addition, the Java regular expression code does not recognize keys such as /g and /i ; they are controlled by constants in java.util.regex.Pattern .

The only Javascript regex switches that make sense in the Java world are /i and /m . They are displayed in Pattern.CASE_INSENSITIVE and Pattern.MULTILINE (you can use these switches when creating a regular expression from the Pattern class, or you can use them inline - I will show this later).

/g doesn't map to anything, but you can control the replacement of behavior using String.replaceAll versus String.replaceFirst .

To make your code work, you need to do something like this:

 strOutput.replaceAll("{{[^]*?}}", ""); 

If you want to use switches, you need to add something like (?i) at the beginning of the regular expression.

You cannot use String.replace because it takes CharSequence for the first argument, not for the regular expression.

Also keep in mind that the “quick re-expression” methods proposed by the String class may not work as you expect. This is because when you specify a pattern (e.g. abc ) as a regular expression for matches , for example, the actual pattern visible to Java is ^abc$ . That way abc will match, but bc won't.

More information here .

+11
source share

Get rid of the "/" and "/g" at the beginning and end of the regular expression. Then you need to avoid each event "\" as follows: "\\" .

The “g” part means global. This is controlled by how you use the regex in Java, and not in the regex string.

+1
source share

You will not need the / (slashes at the beginning and at the end), which are used in javascript for inline declarations instead of quotes.

There should be only Regex r = new Regex("{{[^]*?}}");

0
source share

All Articles