且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 14:32:39

将前导和尾随'/'字符更改为'',然后用\\替换每个'\'

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