有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

要匹配ResourceBundle的java正则表达式

我需要一个正则表达式,它将匹配ResourceBundle的文件名,该文件名遵循name_lo_CA_le.properties格式。它应该只匹配文件名中有区域设置部分的捆绑包,并且名称部分不应有下划线

经过数小时的实验,我得出以下结论:

^[a-zA-Z]+(_([a-z]{2}(_[A-Z]{0,2})?|[a-z]{0,2}(_[A-Z]{2})?){1}(_\\w*)?){1}\\.properties$

这似乎并不适用于所有情况:

"bundle.properties".match(...);               // false - correct
"bundle_.properties".match(...);              // false - correct
"bundle_en.properties".match(...);            // true - correct
"bundle__US.properties".match(...);           // true - correct
"bundle_en_US.properties".match(...);         // true - correct
"bundle_en__Windows.properties".match(...);              // false!
"bundle__US_Windows.properties".match(...);   // true - correct
"bundle_en_US_Windows.properties".match(...); // true - correct

我完全不知道如何从这里开始。以下是我在括号部分背后的推理:

(...){1}正好匹配一个区域设置部分

(_([a-z]{2}(_[A-Z]{0,2})?|[a-z]{0,2}(_[A-Z]{2})?){1}正好匹配两个字符的语言代码和可能为零且最多为2个字符的国家代码中的一个,或者相反

(_\\w*)?匹配一个或没有变体

你知道如何修复和/或改进这个正则表达式吗


共 (4) 个答案

  1. # 1 楼答案

    这对我很有用:

    public class Test {
    
      public static void main(String[] args) {
        String regex = "^[a-zA-Z]+(_)([a-z]{2})?(_)?([A-Z]{2})(_)?(\\w*)(\\.properties)$";
    
        assert "bundle.properties".matches(regex) == false;               // false - correct
        assert "bundle_.properties".matches(regex) == false;              // false - correct
        assert "bundle_en.properties".matches(regex) == false;            // false!
        assert "bundle__US.properties".matches(regex) == true;           // true - correct
        assert "bundle_en_US.properties".matches(regex) == true;         // true - correct
        assert "bundle_en__Windows".matches(regex) == false;             // false!
        assert "bundle__US_Windows.properties".matches(regex) == true;   // true - correct
        assert "bundle_en_US_Windows.properties".matches(regex) == true; // true - correct
      }
    }
    
  2. # 2 楼答案

    这与所有的例子都相符:

    ^[a-zA-Z\_\.]+[A-Z]{0,2}[a-zA-Z\_\.]*.properties$
    
  3. # 3 楼答案

    我最后使用的正则表达式是:

    ^[a-zA-Z.]+(_([a-z]{2}(_[A-Z]{0,2})?|[a-z]{0,2}(_[A-Z]{2})?){1}(_\w*)?)\.properties$
    

    它仍然不匹配没有国家的区域设置部分,如bundle_en__Windows.properties,但这是我能想到的最好的

  4. # 4 楼答案

    你可以尝试以下方法:

    ^[a-zA-Z\_\.]+[A-Z]{2}[a-zA-Z\_\.]*.properties$