Dragan Dragan - 16 days ago 6
Java Question

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.

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()


This is the class that has a loadProperty method

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?

Answer

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()
);
Comments