简体   繁体   English

我可以在 JAVA 的属性文件中使用正则表达式吗?

[英]Can I use regex in properties file in JAVA?

I am trying to assert some text that is stored in properties file:我试图断言存储在属性文件中的一些文本:

Text=\
some text\n\
to be\n\
asserted\n\
based on 1567 ratings

1567 vary so I want to make sure that it get's replaced with regex that will say that this can be any number using \\d or \\d, since I have to escape \\ in properties file. 1567 有所不同,所以我想确保它被替换为正则表达式,它会说这可以是使用 \\d 或 \\d 的任何数字,因为我必须在属性文件中转义 \\。

So I tried using所以我尝试使用

Text=\
some text\n\
to be\n\
asserted\n\
based on \\d ratings

this is the method I am using to assert:这是我用来断言的方法:

Assert.assertEquals(PropertyLoader.loadProperty("filename.properties", "Text"),actual);

actual is a WebElement that gives me the text from website, I use actual.getText() actual 是一个 WebElement,它给我来自网站的文本,我使用actual.getText()

This is the class that has a loadProperty method这是具有 loadProperty 方法的类

class PropertyLoader {
    static String loadProperty(String file, String name) {
        Properties props = new Properties();
        try {
           props.load(getResourceAsStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props.getProperty(name);
    }
}

End result is that i am getting最终结果是我得到

Comparison Failure:比较失败:

Expected:
    some text
    to be
    asserted
    based on \d ratings

Actual:
    some text
    to be
    asserted
    based on 1567 ratings

Not sure if this is even possible or I am simply missing something?不确定这是否可能,或者我只是遗漏了什么?

First the content of your properties file should be:首先,您的属性文件的内容应该是:

Text=\
some text\n\
to be\n\
asserted\n\
based on \\d+ ratings

Then your test case will be:那么你的测试用例将是:

Assert.assertTrue(
    Pattern.compile(
        PropertyLoader.loadProperty("filename.properties", "Text"),  
        Pattern.MULTILINE
    ).matcher(actual).matches()
);

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

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