How to get Locale from its String representation in Java?

前端 未结 12 1063
慢半拍i
慢半拍i 2020-12-08 00:06

Is there a neat way of getting a Locale instance from its \"programmatic name\" as returned by Locale\'s toString() method? An obvious and ugly solution would b

12条回答
  •  孤城傲影
    2020-12-08 00:29

    You can use this on Android. Works fine for me.

    private static final Pattern localeMatcher = Pattern.compile
            ("^([^_]*)(_([^_]*)(_#(.*))?)?$");
    
    public static Locale parseLocale(String value) {
        Matcher matcher = localeMatcher.matcher(value.replace('-', '_'));
        return matcher.find()
                ? TextUtils.isEmpty(matcher.group(5))
                    ? TextUtils.isEmpty(matcher.group(3))
                        ? TextUtils.isEmpty(matcher.group(1))
                            ? null
                            : new Locale(matcher.group(1))
                        : new Locale(matcher.group(1), matcher.group(3))
                    : new Locale(matcher.group(1), matcher.group(3),
                                 matcher.group(5))
                : null;
    }
    

提交回复
热议问题