簡體   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