lisak lisak - 6 months ago 63
Java Question

Get property keys by pattern from ResourceBundleMessageSource in spring

I have almost hundred properties like this

NotEmpty.order.languageFrom=Field Language can't be empty
NotEmpty.order.languageTo=Field Language can't be empty
NotEmpty.order.description=Description field can't be empty
NotEmpty.order.formType=FormType field can't be empty
NotEmpty.cart.formType=FormType field can't be empty
NotEmpty.cart.formType=FormType field can't be empty

And I'd like to be able getting these properties (both keys/values) without previous knowledge of keys ...something like
getPropertyPair(regexp .*.order.[a-z]*=)

Does anybody know if spring or JDK offers something for that ? I suppose I'm gonna have to get the ResourceBundle and get all the keys and regexp them...


I don't think you can do it in Spring, but here's some code that might help:

public class Main {
  public static void main(String[] args) {
    ResourceBundle labels = ResourceBundle.getBundle("spring-regex/regex-resources", Locale.UK);
    Enumeration<String> labelKeys = labels.getKeys();

    // Build up a buffer of label keys
    StringBuffer sb = new StringBuffer();
    while (labelKeys.hasMoreElements()) {
      String key = labelKeys.nextElement();
      sb.append(key + "|");

    // Choose the pattern for matching
    Pattern pattern = Pattern.compile(".*.order.[a-z]*\\|");
    Matcher matcher = pattern.matcher(sb);

    // Attempt to find all matching keys
    List<String> matchingLabelKeys = new ArrayList<String>();
    while (matcher.find()) {

    // Show results
    for (String value: matchingLabelKeys) {
      System.out.format("Key=%s Resource=%s",value,labels.getString(value));



It's a bit hacky but I'm sure you can tidy it up into something more useful.