【问题标题】:Regular expression java read from properties正则表达式 java 从属性中读取
【发布时间】:2014-11-09 05:07:31
【问题描述】:

我在 java 中有一个正则表达式的任务,我有一个问题。

sentences = text.split();

如何从 regexp.properties 文件中将正则表达式传递给 ()

regexp.DECLARATIVE_SENTENCE = "\\."; 

例如。

我可以使用像

这样的常量
public static final String DECLARATIVE_SENTENCE  = "\\.";  

比做

sentences = text.split(DECLARATIVE_SENTENCE);

但我需要从属性文件中读取参数。我怎样才能做到这一点?以资源包为例?

【问题讨论】:

    标签: java regex string properties


    【解决方案1】:

    如果我理解正确,您想从属性文件中加载正则表达式值。

    为此,您可以在 Java 中使用名为 Properties 的类。

    public Properties GetPropertiesFile(String location) throws IOException {
       Properties prop = new Properties();
       FileInputStream inputStream = null;
    
       try
       {
          inputStream = new FileInputStream(location);
          prop.load(inputStream);
       } finally {
          if (inputStream != null) {
             inputStream.close();
          }
       }
    
       return prop;
    }
    

    根据您的情况,您可能需要使用FileInputStream 并使用getClass().getClassLoader().getResourceAsStream,但这应该会让您接近。

    这是你如何使用上面的函数:

    Properties prop = GetPropertiesFile("regexp.properties");
    String regex = prop.getProperty("DECLARATIVE_SENTENCE");
    
    String[] ret = str.split(regex);
    

    您可能必须根据您的配置更改属性文件位置,如果属性文件是资源,甚至可能更改 FileInputStream

    【讨论】:

      【解决方案2】:
      import java.util.ResourceBundle;
      
      ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName);
      rb.getString(DECLARATIVE_SENTENCE)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多