这些特殊字符在Java中意味着什么?

Jou*_*Man 11 java regex

我在看一些jdk代码.我找到了这些角色.有人可以向我解释这些意味着什么.

public static String quote(String s) {
    int slashEIndex = s.indexOf("\\E");        // What does this mean. Is this a special char in java. if so what does this do.
    if (slashEIndex == -1)
        return "\\Q" + s + "\\E";          

    StringBuilder sb = new StringBuilder(s.length() * 2);
    sb.append("\\Q");
    slashEIndex = 0;
    int current = 0;
    while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
        sb.append(s.substring(current, slashEIndex));
        current = slashEIndex + 2;
        sb.append("\\E\\\\E\\Q");
    }
    sb.append(s.substring(current, s.length()));
    sb.append("\\E");
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

从上面的代码示例中,我能够找出正在发生的事情,因为在方法中找到了\的出现并将它们转换为\ E和\ Q. 有人可以解释为什么会这样.

有关此方法的更多上下文,我正在研究jdk 1.6中的Pattern.quote()方法

Kum*_*tra 7

\Q并且\E正是这样Pattern.quote()做的,即返回指定字符串的文字模式字符串。

有关更多详细信息,请参阅此链接:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html


das*_*ght 6

Java的正则表达式引擎块之间的所有元字符特殊的解释\Q\E。例如,[name]与单个字符匹配('n''a''m',或'e'),而\Q[name]\E火柴六个字符- ,'[''n''a''m''e'']'。有关更多详细信息,请参见regex教程的“ 特殊字符”部分。

该方法从大概由外部提供(例如,由用户输入)的字符串中生成正则表达式。由于字符串可能包含元字符,因此该方法将整个字符串括在\Q和中\E。如果字符串中已经包含一个\E,则该方法将\E为其插入的每个引号的末尾,的匹配项和新引号的开头\E