[英]Canonical way to compare locales as subsets of each other
Assume I have a locale stored in some config in whatever format, that I can get a Locale
object from.假设我有一个以任何格式存储在某个配置中的语言环境,我可以从中获取Locale
对象。 I then need to check that the current Locale
is this locale or a subset of this locale .然后我需要检查当前的Locale
是这个 locale还是这个 locale 的一个子集。
So, what I'm looking for, in essence, is a method isSubsetLocale(Locale currentLocale, Locale configLocale)
with these properties:所以,我正在寻找的本质上是一种具有以下属性的方法isSubsetLocale(Locale currentLocale, Locale configLocale)
:
isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("en")) == true;
isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("en-US")) == true;
isSubsetLocale(Locale.forLanguageTag("de-CH"), Locale.forLanguageTag("en")) == false;
// or even
isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("")) == true;
I understand that in 99% of the cases I can just check if the config locale is a prefix of the current locale, but I'm wondering if there's a more idiomatic way to do it.我知道在 99% 的情况下,我可以检查配置语言环境是否是当前语言环境的前缀,但我想知道是否有更惯用的方法来做到这一点。
This might work:这可能有效:
public static boolean isSubsetLocale(Locale locale1, Locale locale2) {
String tag1 = locale1.toLanguageTag();
String tag2 = locale2.toLanguageTag();
if (tag1.equals("und"))
tag1 = "";
if (tag2.equals("und"))
tag2 = "";
return tag1.startsWith(tag2);
}
Test测试
System.out.println(isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("en")));
System.out.println(isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("en-US")));
System.out.println(isSubsetLocale(Locale.forLanguageTag("de-CH"), Locale.forLanguageTag("en")));
System.out.println(isSubsetLocale(Locale.forLanguageTag("en-US"), Locale.forLanguageTag("")));
System.out.println(isSubsetLocale(Locale.forLanguageTag("en"), Locale.forLanguageTag("en-US")));
Output输出
true
true
false
true
false
Do you need something more than locale.getLanguage()
for the comparison?您是否需要比locale.getLanguage()
以外的东西来进行比较? That will give you the prefix for comparison.这将为您提供用于比较的前缀。
Locale.forLanguageTag("en-US").getLanguage().equals(Locale.forLanguageTag("en").getLanguage()) //true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.