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

问题描述 投票:14回答:2

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

String tempAttribute = ((String) attributes.get(i)).replaceAll("\\p{Z}","")

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

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

java regex replaceall
2个回答
12
投票

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

regular-expressions.info提供精彩的正则表达式教程。引用from this site

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


4
投票

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

这个输出是:

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}
            ^

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

这些结果还表明在Java \\ p {Separator}中抛出了PatternSyntaxException。

© www.soinside.com 2019 - 2024. All rights reserved.