js表达式转java,将Javascript正则表达式转换为Java语法

I am aware that regEx are common across languages...But I am having trouble in writing the Java syntax.

I have a regular expression coded in JS as;

if((/[a-zA-Z]/).test(str) && (/[0-9]|[\x21-\x2F|\x3A-\x40|\x5B-\x60|\x7B-\x7E]/).test(str))

return true;

How do I write the same in Java ?

I have imported

import java.util.regex.Matcher;

import java.util.regex.Pattern;

Just to add, from what I am trying it is saying \x is an invalid escape character..

解决方案

Change the leading and trailing '/' characters to '"', and then replace each '\' with "\\".

Unlike, Javascript, Perl and other scripting languages, Java doesn't have a special syntax for regexes. Instead, they are (typically) expressed using Java string literals. But '\' is the escape character in a Java string literal, so each '\' in the original regex has to be escaped with a 2nd '\'. (And if you have a literal backslash character in the regex, you end up with "\\\\" in the Java string literal!!)

This is a bit confusing / daunting for Java novices ... but it is totally logical. Just remember that you are using a Java string literal to express the regex.

However as @antak notes, there are various differences between regex languages in Java and Javascript. So if you take a Javascript regex and transliterate it to Java as above, it might not work.

Here are some references that summarize the differences.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值