Skip to content

Instantly share code, notes, and snippets.

@trygvis
Created April 13, 2011 11:36
Show Gist options
  • Save trygvis/917385 to your computer and use it in GitHub Desktop.
Save trygvis/917385 to your computer and use it in GitHub Desktop.
String to java.util.Locale parser
public class LocaleUtil {
private static Pattern pattern = Pattern.compile("^([a-z][a-z])(_([A-Z][A-Z]))?$");
/**
* Returns null if the string couldn't be parsed
*/
public static Locale parseStringToLocale(String s) {
Matcher matcher = pattern.matcher(s);
if(!matcher.matches()) {
return null;
}
String language = matcher.group(1);
String country = matcher.group(3);
if(country == null) {
return new Locale(language);
}
return new Locale(language, country);
}
}
@hamnis
Copy link

hamnis commented Apr 13, 2011

instead of returning null:
return new Locale("", "");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment