How to detect in Java if string contains Cyrillic?
Try the following:
Pattern.matches(".*\\p{InCyrillic}.*", text)
You may also avoid a regex and use the class Character.UnicodeBlock
:
for(int i = 0; i < text.length(); i++) {
if(Character.UnicodeBlock.of(text.charAt(i)).equals(Character.UnicodeBlock.CYRILLIC)) {
// contains Cyrillic
}
}
Here is another way to do the same with streams in java 8:
text.chars()
.mapToObj(Character.UnicodeBlock::of)
.filter(Character.UnicodeBlock.CYRILLIC::equals)
.findAny()
.ifPresent(character -> ));
Or another way, keeping the index:
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 -> );
Please note: I'm using char array here rather than String due to performance advantage of getting an element by index.