如何转义 java 中的 + 字符?

How to escape + character in java?

如何在 java 中使用拆分函数调用时转义 + 字符?

拆分声明

String[] split(String regularExpression)

我就是这么做的

services.split("+"); //says dongling metacharacter

services.split("\+"); //illegal escape character in string literal

但它允许做这样的事情

String regExpr="+";

由于 + 是正则表达式元字符(表示出现 1 次或多次),您必须使用 \ 对其进行转义(也必须进行转义,因为它是描述制表符、换行符 \r\n 和其他字符时使用的元字符),因此您必须这样做:

services.split("\+");

应该是这样的:

services.split("\+");

Java和Regex都有特殊的转义序列,而且都以\开头。

您的问题在于在 Java 中写入字符串文字。 Java 的转义序列在编译时解析,远早于将字符串传递到正则表达式引擎进行解析。

序列 "\+" 会抛出错误,因为这不是有效的 Java 字符串。

如果你想将 \+ 传递到你的正则表达式引擎中,你必须明确地让 Java 知道你想使用 "\+".

传递一个反斜杠字符

所有有效的Java转义序列如下:

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\  Insert a backslash character in the text at this point.