js正则 java正则,如何将javascript正则表达式转换为安全的java正则表达式?

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!

解决方案

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

There is more information here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值