问题描述:

I need to compare the date in the field corresponds to the current day.

In selenium ide is solved very simply:

<tr>

<td>storeExpression</td>

<td>javascript{var date = new Date();date.getDate()+' '+date.getMonth();}</td>

<td>t_date</td>

</tr>

<tr>

<td>storeExpression</td>

<td>javascript{var date = new Date();(date.getDate() -1)+' 'date.getMonth();}</td>

<td>y_date</td>

</tr>

<tr>

<td>assertText</td>

<td>//div[@id='a-articles-container']/a[3]/span[2]/span[2]/span[2]</td>

<td>regexp:(${t_date}*)|(${y_date}*)</td>

</tr>

But when I export the html code in java, I get an illegal repetition: Pattern.compile("(${t_date}*)|(${y_date}*)")

My java code looks like this:

Calendar c = Calendar.getInstance();

String t_date = c.get(c.DAY_OF_MONTH) + " " + c.get(c.MONTH);

String y_date = (c.get(c.DAY_OF_MONTH)-1) + " " + c.get(c.MONTH);

assertTrue(Pattern.compile("(${t_date}*)|(${y_date}*)").matcher(driver.findElement(By.xpath("//div[@id='a-articles-container']/a[5]/span[2]/span[2]/span[2]")).getText()).find());

I can compare the text with variable y_date

assertTrue(Pattern.compile(y_date).matcher(driver.findElement(By.xpath("//div[@id='a-articles-container']/a[5]/span[2]/span[2]/span[2]")).getText()).find());

or t_date

 assertTrue(Pattern.compile(t_date).matcher(driver.findElement(By.xpath("//div[@id='a-articles-container']/a[5]/span[2]/span[2]/span[2]")).getText()).find());

But not with both at once!

How can I use "or" operator in a pattern to compare the explanatory variables is whether the text?

网友答案:

Java does not support String Interpolation like Ruby, PHP etc. so you cannot write "${variable}" and expect it to work. What is happening in your case is the ${t_date} is remaining in that form and Pattern.compile is trying to interpret it as a regular expression, and { and } are reserved characters.

However String.format with using placeholders like %s works as a good substitute.

What I believe you want is the following.

assertTrue(Pattern.compile(String.format("(%s*)|(%s*)", t_date, y_date))
        .matcher(driver.findElement(By.xpath("//div[@id='a-articles-container']/a[5]/span[2]/span[2]/span[2]")).getText()).find());
相关阅读:
Top