Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 由Pattern.LITERAL解析的正则表达式中的转义序列_Java_Regex - Fatal编程技术网

Java 由Pattern.LITERAL解析的正则表达式中的转义序列

Java 由Pattern.LITERAL解析的正则表达式中的转义序列,java,regex,Java,Regex,给出以下代码段: Pattern pt = Pattern.compile("\ndog", Pattern.LITERAL); Matcher mc = pt.matcher("\ndogDoG"); while(mc.find()) { System.out.printf("I have found %s starting at the " + "index %s and ending at the index %s%n",mc.group(),mc.

给出以下代码段:

Pattern pt = Pattern.compile("\ndog", Pattern.LITERAL);
Matcher mc = pt.matcher("\ndogDoG");
while(mc.find())
{

    System.out.printf("I have found %s starting at the " +
            "index %s and ending at the index    %s%n",mc.group(),mc.start(),mc.end());

}
输出将是:

I have found 
dog starting at the index 0 and ending at the index 4.
这意味着,即使我已经指定了
Pattern.LITERAL
,这表示:

Pattern.LITERAL启用模式的文本解析。当这面旗子 则指定模式的输入字符串为 被视为一系列文字字符。元字符或转义 输入序列中的序列没有特殊意义

但是,上面代码段给出的输出确实解释了转义序列
\n
,它并没有将其视为文本

既然他们在教程中指定不应该这样做,为什么会这样呢


I现在\n是一个行终止符,但它仍然是一个转义序列字符。

模式。LITERAL
关心正则表达式文字,而不是字符串文字

因此,它将
\\n
视为
反斜杠
n
(而不是换行符的regex标记),但将
\n
视为它所代表的换行符(因此忽略它)

然而,它仍然是一个转义序列字符

不,不是。这是一个换行符。你可以做:

char c = '\n';
因此,您的输出是预期的

请注意,如果编译模式时使用:

Pattern.compile("\n")
然后
\n
是文本字符
\n

但如果使用以下工具编译:

Pattern.compile("\\n")
然后是一个逃逸序列。而且它们恰好匹配相同的东西