java从输入字符串中的数组中搜索关键字并打印它们
我几乎从过去几天就开始这样做了,但仍然无法获得所需的输出。
我有一个数组要说
wordlist[]={"One","Two","Three","Four","Five"};
然后我从用户那里获取输入
String input="I have three no, four strings";
现在我要做的是对字符串执行搜索操作,以检查数组wordlist[]中可用的单词; 与上面的示例类似,输入字符串包含数组中的单词3和4。 因此,它应该能够从字符串中可用的数组中打印这些单词,如果wordlist[]中没有可用的单词,那么它应该打印“找不到匹配项”
这是我的密码,我很惊讶。 请
import java.util.regex.*;
import java.io.*;
class StringSearch{
public static void main(String ...v)throws IOException{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String wordlist[]={"one","two","three","four","five"};
String input=cin.readLine();
int i,j;
boolean found;
Pattern pat;
Matcher mat;
Pattern spliter=Pattern.compile("[ ,.!]");
String ip[]=spliter.split(input);
System.out.println(ip[2]);
for(i=0; i<wordlist.length;i++){
for(j=0;j<ip.length;j++){
pat=Pattern.compile("\b"+ip[j]+"\b");
mat=pat.matcher(wordlist[i]);
if(){
// No Idea What to write here
}
}
}
}
}
# 1 楼答案
您需要将
matches
与条件input.matches(".*\\b"+wordlist[i]+"\\b.*")
一起使用.*
:匹配任何内容\\b
:避免将four
与fourteen
匹配的单词边界而
wordlist[i]
是你的话1.)使用循环遍历数组
(二)从数组中选取单词并对给定的正则表达式使用
matches
,以避免将four
与fourteen
匹配输出:
# 2 楼答案
使用Java8流,您可以执行以下操作:
# 3 楼答案
这里准备一个正则表达式:\\b(一|二|三|四|五)\\b并检查匹配器的计数