简体   繁体   English

从java中的属性文件中读取正则表达式

[英]Read regex from properties file in java

I have problem reading values like (\\+?\\s*[0-9]+\\s*)+ from properties file in java, because the value , what I get with getProperty() method is (+?s*[0-9]+s*)+ . 我在java中的属性文件中读取(\\+?\\s*[0-9]+\\s*)+等值时遇到问题,因为我用getProperty()方法得到的值是(+?s*[0-9]+s*)+

Escaping of values in properties file is not an option yet. 在属性文件中转义值不是一个选项。

Any ideas? 有任何想法吗?

I think this class could be solution for the backslash problem in properties file. 我认为这个类可以解决属性文件中的反斜杠问题。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class ProperProps {

    HashMap<String, String> Values = new HashMap<String, String>();

    public ProperProps() {
    };

    public ProperProps(String filePath) throws java.io.IOException {
        load(filePath);
    }

    public void load(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.trim().length() == 0 || line.startsWith("#"))
                continue;

            String key = line.replaceFirst("([^=]+)=(.*)", "$1");
            String val = line.replaceFirst("([^=]+)=(.*)", "$2");
            Values.put(key, val);

        }
        reader.close();
    }


    public String getProperty(String key) {
        return Values.get(key);
    }


    public void printAll() {
        for (String key : Values.keySet())
            System.out.println(key +"=" + Values.get(key));
    }


    public static void main(String [] aa) throws IOException {
        // example & test 
        String ptp_fil_nam = "my.prop";
        ProperProps pp = new ProperProps(ptp_fil_nam);
        pp.printAll();
    }
}

I am pretty late to answer this question, but maybe this could help others that end up here. 我很晚才回答这个问题,但也许这可以帮助其他人到达这里。

Newer versions of Java (not sure which, I am using 8) support escaping of values by using \\\\ to represent the normal \\ we are used to. 较新版本的Java(不确定哪个,我使用8)通过使用\\\\来表示我们习惯的普通\\来支持转义值。

For example, in your case, (\\\\+?\\\\s*[0-9]+\\\\s*)+ is what you are looking for. 例如,在您的情况下, (\\\\+?\\\\s*[0-9]+\\\\s*)+就是您要找的。

Just read using a classical BufferedReader instead: 只需使用经典的BufferedReader读取:

final URL url = MyClass.class.getResource("/path/to/propertyfile");
// check if URL is null;

String line;

try (
    final InputStream in = url.openStream();
    final InputStreamReader r 
        = new InputStreamReader(in, StandardCharsets.UTF_8);
    final BufferedReader reader = new BufferedReader(r);
) {
    while ((line = reader.readLine()) != null)
        // process line
}

Adapt to Java 6 if necessary... 必要时适应Java 6 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM