繁体   English   中英

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

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

我试图断言存储在属性文件中的一些文本:

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

1567 有所不同,所以我想确保它被替换为正则表达式,它会说这可以是使用 \\d 或 \\d 的任何数字,因为我必须在属性文件中转义 \\。

所以我尝试使用

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

这是我用来断言的方法:

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

actual 是一个 WebElement,它给我来自网站的文本,我使用actual.getText()

这是具有 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);
    }
}

最终结果是我得到

比较失败:

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

Actual:
    some text
    to be
    asserted
    based on 1567 ratings

不确定这是否可能,或者我只是遗漏了什么?

首先,您的属性文件的内容应该是:

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

那么你的测试用例将是:

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