通过比较java中的字符串模式,有没有简单的方法来提取单词。
input
pattern: what do you know about <topic1> and <topic2>
string : what do you know about cricket and football
output
cricket, football
答案 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");
以上行也可以。