将Javascript正则表达式转换为Java语法 [英] Convert Javascript regular expression to Java syntax
问题描述
我知道regEx在各种语言中很常见......但是我在编写Java语法时遇到了麻烦。
我有一个用JS编码的正则表达式;
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;
如何在Java中编写相同的内容?
How do I write the same in Java ?
我已导入
import java.util.regex.Matcher;
import java.util.regex.Pattern;
只是添加,我正在尝试它是说\ x是一个无效的转义字符。 。
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 "\\"
.
与Javascript,Perl和其他脚本语言不同,Java没有针对正则表达式的特殊语法。相反,它们是(通常使用Java字符串文字表示。但'\'
是Java字符串文字中的转义字符,因此每个'\'$原始正则表达式中的c $ c>必须使用第二个
'\'
进行转义。(如果你在正则表达式中有一个字面反斜杠字符,你最终会得到Java字符串文字中的\\\\
!!)
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!!)
这是一点点让Java新手感到困惑/畏惧......但这完全是合乎逻辑的。记住这一点在你使用Java字符串文字来表达正则表达式。
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.
然而正如@antak所说,两者之间存在各种差异Java和Javascript中的正则表达式语言。因此,如果您使用Javascript正则表达式并将其音译为Java,则可能无效。
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.
- https://en.wikipedia.org / wiki / Comparison_of_regular_expression_engines
- https:// gist。 github.com/CMCDragonkai/6c933f4a7d713ef712145c5eb94a1816
- https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines
- https://gist.github.com/CMCDragonkai/6c933f4a7d713ef712145c5eb94a1816
这篇关于将Javascript正则表达式转换为Java语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!