正则表达式"\\ p {Z}"是什么意思?

BRa*_*t27 15 java regex replaceall

我正在使用java中的一些代码,它具有类似的语句

String tempAttribute = ((String) attributes.get(i)).replaceAll("\\p{Z}","")
Run Code Online (Sandbox Code Playgroud)

我不习惯正则表达式,所以它的含义是什么?(如果你能提供一个网站来学习那些很棒的正则表达式的基础知识)我已经看到了像

ept as y它变成了eptasy,但这似乎不对.我相信写这篇文章的人想要修剪前导空格和尾随空格.

Ale*_*rov 14

它删除所有空格(用空字符串替换所有空格匹配).

一个精彩的正则表达式教程可以在regular-expressions.info上找到.来自这个网站的引用:

\ p {Z}或\ p {Separator}:任何类型的空格或不可见的分隔符.

  • 反斜杠在程序代码中加倍,因为它是字符串文字的Java语法.Java编译器从中产生一个反斜杠,带有一个斜杠的字符串传递给Regex引擎.请参阅[正则表达式教程,"特殊字符和编程语言"部分](http://www.regular-expressions.info/characters.html) (8认同)

小智 7

首先, \p这意味着您将匹配一个类、一组字符,而不是单个字符。作为参考,这是 Pattern 类的 Javadoc。https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Unicode 脚本、块、类别和二进制属性是用 \p 和 \P 结构编写的,就像 Perl 中一样。如果输入具有属性 prop,则 \p{prop} 匹配,而如果输入具有该属性,则 \P{prop} 不匹配。

然后Z是字符类(集合、集合)的名称。在本例中,它是 的缩写SeparatorSeparator包含 3 个子类:Space_Separator(Zs)、Line_Separator(Zl) 和Paragraph_Separator(Zp)。

请参阅此处了解这些类包含哪些字符:Unicode 字符数据库Unicode 字符类别

更多文档:http://www.unicode.org/reports/tr18/#General_Category_Property


小智 5

OP指出代码片段是用Java编写的。对声明发表评论:

\ p {Z}或\ p {Separator}:任何类型的空格或不可见的分隔符。

下面的示例代码显示这不适用于Java。

public static void main(String[] args) {

    // some normal white space characters
    String str = "word1 \t \n \f \r " + '\u000B' + " word2"; 

    // various regex patterns meant to remove ALL white spaces
    String s = str.replaceAll("\\s", "");
    String p = str.replaceAll("\\p{Space}", "");
    String b = str.replaceAll("\\p{Blank}", "");
    String z = str.replaceAll("\\p{Z}", "");

    // \\s removed all white spaces
    System.out.println("s [" + s + "]\n"); 

    // \\p{Space} removed all white spaces
    System.out.println("p [" + p + "]\n"); 

    // \\p{Blank} removed only \t and spaces not \n\f\r
    System.out.println("b [" + b + "]\n"); 

    // \\p{Z} removed only spaces not \t\n\f\r
    System.out.println("z [" + z + "]\n"); 

    // NOTE: \p{Separator} throws a PatternSyntaxException
    try {
        String t = str.replaceAll("\\p{Separator}","");
        System.out.println("t [" + t + "]\n"); // N/A
    } catch ( Exception e ) {
        System.out.println("throws " + e.getClass().getName() + 
                " with message\n" + e.getMessage());
    }

} // public static void main
Run Code Online (Sandbox Code Playgroud)

输出为:

s [word1word2]

p [word1word2]

b [word1


word2]

z [word1    


word2]

throws java.util.regex.PatternSyntaxException with message
Unknown character property name {Separator} near index 12
\p{Separator}
            ^
Run Code Online (Sandbox Code Playgroud)

这表明在Java中\\ p {Z}仅删除空格,而不删除“任何种类的空白或不可见分隔符”。

这些结果还表明,在Java \\ p {Separator}中引发了PatternSyntaxException。