最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to convert javascript regex to safe java regex? - Stack Overflow

programmeradmin1浏览0评论
strOutput.replace("/{{[^]*?}}/g","");

Is there a way to convert JavaScript regexes to Java-safe regexes?

The above statement gives me the error:

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

I'm not all that familiar with regex, so I could use some guidance.

Thanks!

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

Is there a way to convert JavaScript regexes to Java-safe regexes?

The above statement gives me the error:

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

I'm not all that familiar with regex, so I could use some guidance.

Thanks!

Share Improve this question edited Jan 25, 2011 at 11:43 Alan Moore 75.2k13 gold badges107 silver badges160 bronze badges asked Jan 24, 2011 at 23:30 rockitrockit 3,7967 gold badges28 silver badges36 bronze badges 1
  • 1 Can you post the Java you've created that gave you the error? – Peter Bailey Commented Jan 24, 2011 at 23:37
Add a comment  | 

3 Answers 3

Reset to default 14

Get rid of the forward slashes. You don't need those in Java. Also, Java's flavor of regex doesn't recognize switches like /g and /i; those 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. These map to Pattern.CASE_INSENSITIVE and Pattern.MULTILINE (you can use these switches when creating a regex from the Pattern class, or you can use them inline -- I'll show this later).

The /g doesn't map to anything, but you can control replace behavior by using String.replaceAll versus String.replaceFirst.

To get your code to work, you'd have to do something like this:

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

If you wanted to use switches, you need to do add something like (?i) to the beginning of the regex.

You can't use String.replace because it takes in a CharSequence for the first argument and not a regex.

Also keep in mind that the "quick regex" methods offered by the String class may not work like you expect it to. This is because when you specify a pattern (let's say abc) as a regex for matches for example, the actual pattern seen by Java is ^abc$. So abc will match, but abcd will not.

There is more information here.

Get rid of "/" and "/g" at the start and the end of regex. Then you need to escape every "\" occurrence like so: "\\".

The "g" part means global. This is controlled in how you use regex in Java as opposed to in the regex string.

You wouldn't need the /'s (forward slashes at start and end) those are used in javascript for inline declaration instead of quotes.

Should just be Regex r = new Regex("{{[^]*?}}"); ​​​​

发布评论

评论列表(0)

  1. 暂无评论