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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript正则表达式Java正则表达式在语法上有一些差异,但是它们的基本概念和用法是相似的。下面是将JavaScript正则表达式转换Java正则表达式的一些常见规则: 1. 语法差异: - JavaScript正则表达式使用斜杠(/)作为定界符,而Java正则表达式使用双引号(")作为定界符。 - JavaScript正则表达式中的特殊字符需要进行转义,而Java正则表达式中的特殊字符不需要转义。 2. 字符类: - JavaScript正则表达式中的字符类使用方括号([])表示,而Java正则表达式中使用方括号([])或者Unicode转义(\p{...})表示。 - JavaScript正则表达式中的字符类可以使用连字符(-)表示范围,而Java正则表达式中需要使用Unicode转义(\uXXXX)表示范围。 3. 量词: - JavaScript正则表达式中的量词使用花括号({})表示,而Java正则表达式中使用花括号({})或者问号(?)表示。 - JavaScript正则表达式中的贪婪量词默认是贪婪模式,而Java正则表达式中的贪婪量词需要在后面添加问号(?)来表示非贪婪模式。 4. 边界匹配: - JavaScript正则表达式中的边界匹配使用插入符号(^)和美元符号($)表示,而Java正则表达式中使用\A和\Z表示。 5. 其他差异: - JavaScript正则表达式中的捕获组使用圆括号(())表示,而Java正则表达式中使用圆括号(())或者方括号([])表示。 - JavaScript正则表达式中的反向引用使用反斜杠加数字(\1、\2等)表示,而Java正则表达式中使用美元符号加数字($1、$2等)表示。 以上是一些常见的JavaScript正则表达式转换Java正则表达式的规则。具体转换时,还需要根据具体的正则表达式进行适当的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值