如果字符串包含西里尔文,如何在Java中检测?

时间:2016-02-26 20:02:06

标签: java regex

我想检测一个字符串是否包含西里尔字母。

在PHP中,我做了类似的事情:

preg_match('/\p{Cyrillic}+/ui', $text)

Java中的工作原理是什么?

2 个答案:

答案 0 :(得分:18)

尝试以下方法:

Pattern.matches(".*\\p{InCyrillic}.*", text)

您也可以避免使用正则表达式并使用课程Character.UnicodeBlock

for(int i = 0; i < text.length(); i++) {
    if(Character.UnicodeBlock.of(text.charAt(i)).equals(Character.UnicodeBlock.CYRILLIC)) {
        // contains Cyrillic
    }
}

答案 1 :(得分:1)

这是对Java 8中的流执行相同操作的另一种方法:

text.chars()
        .mapToObj(Character.UnicodeBlock::of)
        .filter(Character.UnicodeBlock.CYRILLIC::equals)
        .findAny()
        .ifPresent(character -> ));

或者通过另一种方式,保持索引:

char[] textChars = text.toCharArray();
IntStream.range(0, textChars.length)
                 .filter(index -> Character.UnicodeBlock.of(textChars[index])
                                .equals(Character.UnicodeBlock.CYRILLIC))
                 .findAny() // can use findFirst()
                 .ifPresent(index -> );

请注意:由于在索引上获得元素的性能优势,因此我在这里使用char数组而不是String。