【问题标题】:Java Webdriver count first name without last nameJava Webdriver计算没有姓氏的名字
【发布时间】:2017-03-01 18:31:05
【问题描述】:

我正在编写一个 selenium webdriver java 测试,并试图计算出现的名字后面没有姓氏的数量。

例如,任何时候出现“John Smith”都不会被计算在内,但如果是“John did this”这样的句子,由于Smith没有出现,就会增加计数。

不幸的是,无论我做什么,尝试从 WebElement 读取/计数都会返回 0,但我知道无论哪种方式我都不会排除姓氏条目。欢迎提出任何建议!

当前代码:

//get string from WebElement text
 `String john = JohnSmith.getText();
    int johnCount =0;
    while (john.contains("john")){
        johnCount++;

//this line starts from the substring after the first john
        john = john.substring(john.indexOf("john") + "john".length());
    }

【问题讨论】:

  • 你需要正则表达式来做一些过滤

标签: java selenium selenium-webdriver count


【解决方案1】:

我的第一个想法是做一些简单的事情,比如用“”替换“John Smith”,然后计算“John”的实例。 One simple way 计数实例是使用“John”拆分字符串并计数。

一个简单的例子:

String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
s = s.replaceAll("John Smith", "");
int count = s.split("John").length - 1;
System.out.println(count); // 2

编辑: ...或者更好的是,把它变成一个可以轻松重用的函数...

public int countFirstNames(String firstName, String lastName, String searchText)
{
    searchText = searchText.replace(firstName + " " + lastName, "");
    return searchText.split("John").length - 1;
}

然后这样称呼它

String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
System.out.println(countFirstNames("John", "Smith", s)); // 2

【讨论】:

  • 谢谢。我最终得到了一种效率低得多的方法。我用 StringUtils.countMatches(THESTRING, "john");然后减去 StringUtils.countMatches(THE STRING, "john smith");这是在调用 tolower 之后,以防任何名称的格式不正确。
猜你喜欢
  • 2016-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多