如何在Java中检测字符串是否包含西里尔字母?

如何在Java中检测字符串是否包含西里尔字母?,java,regex,Java,Regex,我想检测字符串是否包含西里尔字母 在PHP中,我做了如下操作: preg_match('/\p{Cyrillic}+/ui', $text) 在Java中,什么方法同样有效?请尝试以下方法: Pattern.matches(".*\\p{InCyrillic}.*", text) 您也可以避免使用正则表达式并使用类: for(int i=0;i

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

在PHP中,我做了如下操作:

preg_match('/\p{Cyrillic}+/ui', $text)
在Java中,什么方法同样有效?

请尝试以下方法:

Pattern.matches(".*\\p{InCyrillic}.*", text)
您也可以避免使用正则表达式并使用类:

for(int i=0;i
以下是另一种在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数组而不是字符串。

我想如果我避免使用正则表达式,性能会更好?如果有什么不同的话,我会使用Android。@knezmilos我想你不会注意到有什么大的不同(这取决于文本的大小——你可以尝试两种方式测量)。我更喜欢第二种方式,因为它更清晰。
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 -> );