I want to detect if a string contains Cyrillic letters.
In PHP I did something like this:
preg_match('/\p{Cyrillic}+/ui', $text)
What would work the same in Java?
Java String contains. The java string contains() method searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.
Let us discuss this method implementation through various examples. Java String’s contains () method checks for a particular sequence of characters present within a string. This method returns true if the specified character sequence is present within the string, otherwise, it returns false.
Java String contains() The java string contains() method searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.
Time Complexity: O (N), where N is the length of the given string. Using Character.isDigit (char ch): The idea is to iterate over each character of the string and check whether the specified character is a digit or not using Character.isDigit (char ch).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With