如何将javascript正则表达式转换为安全的java正则表达式? [英] How to convert javascript regex to safe java regex?

查看:524
本文介绍了如何将javascript正则表达式转换为安全的java正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有没有办法将JavaScript正则表达式转换为Java安全正则表达式?

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

以上陈述给出了错误:


无效的转义序列(有效的转义序列)是\b \t \ n \f \ r \\'\\)

我不是那么熟悉正则表达式,所以我可以使用一些指导。

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

谢谢!

推荐答案

摆脱正斜杠。你不需要Java中的那些。而且,Java的正则表达式无法识别像这样的开关/ g / i ;这些由 java.util.regex.Pattern

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.

在Java世界中唯一有意义的Javascript正则表达式开关是 / i / m 。这些映射到 Pattern.CASE_INSENSITIVE Pattern.MULTILINE (你可以使用这些开关在从 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).

/ g 不会映射到任何内容,但您可以使用 String.replaceAll String.replaceFirst

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("{{[^]*?}}", "");

如果你想使用开关,你需要添加类似的东西( ?i)到正则表达式的开头。

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

你不能使用 String.replace 因为第一个参数而不是正则表达式需要 CharSequence

另请注意, String 类提供的快速正则表达式方法可能无法像您期望的那样工作。这是因为当您指定模式(例如 abc )作为的正则表达匹配时,实际模式Java看到的是 ^ abc $ 。所以 abc 将匹配,但 bc 不会。

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 bc will not.

此处提供了更多信息。

这篇关于如何将javascript正则表达式转换为安全的java正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆