通过匹配字符串模式从字符串中提取单词

时间:2018-01-14 15:49:49

标签: java string

通过比较java中的字符串模式,有没有简单的方法来提取单词。

input
pattern: what do you know about <topic1> and <topic2>
string : what do you know about cricket and football

output
cricket, football

1 个答案:

答案 0 :(得分:3)

Pattern p = Pattern.compile("what do you know about (.*) and (.*)"; // in line you create a pattern to which you are checking other Strings
Matcher m = p.matcher(stringToCompare); // in this line you decide that you want to check stringToCompare if it matches the given pattern
while(m.find()) { // this loop prints only captured groups if match was found
    System.out.println(m.group(1)) +" " + m.group(2));
}

Pattern中有捕获组(在括号中),它们的顺序从1开始,从左到右计算它们的出现次数。在while循环中,您决定只将这些组打印到控制台。

在以下行中,您不需要传递对变量的引用,您可能还希望将String字面值传递给Matcher而不是引用String变量:< / p>

Matcher m = p.matcher("what do you know about cricket and football");

以上行也可以。