不区分大小写的POSIX正则表达式在Java Pattern&Matcher中不区分大小写

时间:2018-12-23 22:51:02

标签: java regex string pattern-matching posix

我不是Regex专家,这可能是很明显的原因,但是我找不到答案。

我使用POSIX表示法,以不区分大小写的方式在Java中使用Regex匹配字符串(n。鉴于:

Pattern pattern = Pattern.compile("\\p{Upper}", Pattern.CASE_INSENSITIVE); 
Matcher matcher = pattern.matcher("n");

为什么以下代码导致false

boolean find = matcher.find();

Pattern文档中,我发现了以下内容(强调了我的意思):

  

\ p {Upper} 大写字母字符: [A-Z]

经过正则表达式[A-Z]的测试,在true中得到以下结果:

Pattern pattern = Pattern.compile("[A-Z]", Pattern.CASE_INSENSITIVE); 
Matcher matcher = pattern.matcher("n");
boolean find = matcher.find();

有什么区别?

2 个答案:

答案 0 :(得分:1)

是非是非-Posix字符类会忽略CASE_INSENSITIVE标志。尽管\p{Upper}的工作方式与[A-Z]类似,但它并不完全相同-也不考虑不区分大小写的标志。

Pattern类中用于检查posic字符类的代码未引用CASE_INSENSITIVE标志:

/**
 * Node class that matches a POSIX type.
 */
static final class Ctype extends BmpCharProperty {
    final int ctype;
    Ctype(int ctype) { this.ctype = ctype; }
    boolean isSatisfiedBy(int ch) {
        return ch < 128 && ASCII.isType(ch, ctype);
    }
}

答案 1 :(得分:1)

根据POSIX规范(IEEE 1003):

  

9.2正则表达式一般要求

     

当使用正则表达式的标准实用程序或函数指定执行模式匹配时,不考虑数据或模式的大小写(大写或小写),那么当字符串中的每个字符都与模式匹配时,则不只能匹配字符,还应匹配其对应的大小写(如果有)。

使用POSIX字符类时,Pattern.CASE_INSENSITIVE不会忽略大小写对应检查。