Java 检查字符串中数值的外观(并从中提取)
我正在尝试使用Eclipse中的Selenium通过提交按钮自动化工作流 我正在使用一个自定义函数waitForVisible来检查id为“naviInfo”的WebElement是否显示,以及它是否包含一条消息,该消息包含“未找到任何行”或“已找到{number}行”消息 问题是我无法对文本的数字部分进行排序和检查。下面给出了示例代码Java 检查字符串中数值的外观(并从中提取),java,regex,testing,Java,Regex,Testing,我正在尝试使用Eclipse中的Selenium通过提交按钮自动化工作流 我正在使用一个自定义函数waitForVisible来检查id为“naviInfo”的WebElement是否显示,以及它是否包含一条消息,该消息包含“未找到任何行”或“已找到{number}行”消息 问题是我无法对文本的数字部分进行排序和检查。下面给出了示例代码 String message = waitForVisible(By.id("naviInfo")).getText(); if ("No rows were
String message = waitForVisible(By.id("naviInfo")).getText();
if ("No rows were found".equals(message)) {
log.info("No rows were found after submit");
}
else if ("**1804** rows were found".equals(message)) {
log.info("**1804** rows found after submit");
}
else {
(other error checks)
}
如何检查在公共文本“rows was found”之前是否找到了一个数值?另外,还可以将此数字保存到变量中?如果我没有弄错,您只需要询问如何验证消息是否与预期模式匹配,以及如何从字符串中提取数字?在这种情况下,这与硒无关,而是一个简单的正则表达式问题
Pattern p = Pattern.compile("^\\*{2}(\\d+)\\*{2} rows were found$"); //pattern that says: start of string, followed by two *s, then some digits, then two *s again, then the string " rows were found", and finally the end of string, capturing the digits only
Matcher m = p.matcher("**1804** rows were found");
boolean found = m.find(); //find and capture the pattern of interest
if (found)
int count = Integer.parseInt(m.group(1)); //get the first (and only) captured group, and parse the integer from it
请阅读Java正则表达式。这就是我如何使我的条件起作用的
if (" no rows were found".equals(waitForVisible(By.id("naviInfo")).getText()))
waitForVisible(By.xpath("//td[contains(text(),'Nothing found to display.')]"));
else if (Pattern.matches("^ \\d+ rows were found$", waitForVisible(By.id("naviInfo")).getText()))
waitForVisible(By.xpath("//tbody//tr//td/a"));
else
other error checks
谢谢卡卡。你的评论真的帮我弄明白了我需要什么。