Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex not matching (russian)

Tags:

java

regex

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));
        }
    }
}
like image 260
dj1121 Avatar asked Jul 13 '26 09:07

dj1121


2 Answers

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);
like image 135
Volodymyr Kononenko Avatar answered Jul 14 '26 22:07

Volodymyr Kononenko


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

like image 23
Kamil Piwowarski Avatar answered Jul 15 '26 00:07

Kamil Piwowarski