Trying to match a string "Манихина Галина Владимировна" and others of the same format. That is, a proper name with three words. I'm new to regex and am not sure what's wrong with my statement.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String [] args){
String temp = "Манихина Галина Владимировна";
Pattern pattern = Pattern.compile("^[а-я]+\\s[а-я]+\\s[а-я]+$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(temp);
if (matcher.find()){
System.out.println(matcher.group(0));
}
}
}
According to Java documentation documentation regexp does not match unicode:
By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched
In order to make your code working, add UNICODE_CASE flag:
Pattern pattern = Pattern.compile("^[а-я]+\\s[а-я]+\\s[а-я]+$",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Java by default doesn't properly match unicode text when using character classes: ( \\s in your code). You have to use UNICODE_CHARACTER_CLASS in order to use predefined classes like the whitespace character class you used in your pattern.
So working Pattern.compile usage would be:
Pattern pattern = Pattern.compile("^[а-я]+\\s[а-я]+\\s[а-я]+$",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS);
When you add UNICODE_CHARACTER_CLASS, you also imply using UNICODE_CASE flag - which is necessary for CASE_INSENSITIVE flag to work with unicode characters
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