How to detect in Java if a string contains Cyrillic?

I want to determine if a string contains Cyrillic letters.

In PHP, I did something like this:

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

What will work in Java?

+8
source share
2 answers

Try the following:

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

You can also avoid regex and use the Character.UnicodeBlock class:

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

Here is another way to do the same with threads in Java 8:

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

Or in 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 am using an array of characters here, not String, due to the performance advantage when retrieving an item by index.

+1
source

Source: https://habr.com/ru/post/1243970/


All Articles