gpt4 book ai didi

java - 为什么没有像 Java 中的 for\\t、\\n、\\r 和\\f 那样针对退格字符 ("\b") 的特殊正则表达式构造?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:02 29 4
gpt4 key购买 nike

我想知道为以下字符提供特殊正则表达式结构的原因是什么:

\t - 制表符 ('\u0009')

\n - 换行(换行)字符 ('\u000A')

\r - 回车符 ('\u000D')

\f - 换页符 ('\u000C')

并且,另一方面,不提供退格字符 (\b)。

this question所示,“\\n”与“\n”或“\\t”与“\t",当使用 Pattern.COMMENTS 标志时,但我认为它没有回答这个问题,为什么没有退格字符的正则表达式构造。

退格字符的正则表达式构造是否没有任何可能的用例,不仅是当 Pattern.COMMENTS 标志设置为 Activity 时,而且可能在我不知道的其他情况下然而?为什么退格字符被认为与上面列出的其他空白字符不同,导致决定不为退格字符提供正则表达式构造?

最佳答案

Java 正则表达式起源于 Perl 正则表达式,其中已经定义了大多数速记类。由于 Perl 正则表达式用户习惯于使用 "\\b" 作为单词边界更改,因此已经被接受并且是众所周知的速记。 "\\b" 在 Perl regex 中匹配一个单词边界,它在 Java regex 中带有这个含义。看这个Java regex documentation :

The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary.

目前,你甚至不能让 "\\b" 充当字符集内的退格键(就像在其他一些语言中一样,例如在 Python 中),这样做是专门为了避免人类编写模式时的错误。根据最新规范

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language.

如果您必须对退格键使用正则表达式转义,请使用 Unicode 正则表达式转义 "\\u0008":

Java online demo :

String s = "word1 and\bword2";
System.out.println(Arrays.toString(s.split("\\b"))); // WB
// => [word1, , and, , word2]
System.out.println(Arrays.toString(s.split("\b"))); // BS
// => [word1 and, word2]
System.out.println(Arrays.toString(s.split("[\b]"))); // BS in a char set
// => [word1 and, word2]
System.out.println(Arrays.toString(s.split("\\u0008"))); // BS as a Unicode regex escape
// => [word1 and, word2]
System.out.println(Arrays.toString(s.split("[\\b]")));// WB NOT treated as BS in a char set
// => java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 2

关于java - 为什么没有像 Java 中的 for\\t、\\n、\\r 和\\f 那样针对退格字符 ("\b") 的特殊正则表达式构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49030976/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com