IVA*_*AUL 1 java regex string search string-search
我几乎在过去的几天里一直这样做,但仍然无法获得所需的输出.好吧,我有一个数组说
wordlist[]={"One","Two","Three","Four","Five"};
,然后我接受用户的输入.
String input="I have three no, four strings";
Run Code Online (Sandbox Code Playgroud)
现在我想要做的是对字符串执行搜索操作以检查数组wordlist []中可用的单词; 与上面的示例类似,输入字符串包含数组中存在的单词three和four.所以它应该能够从字符串中可用的数组中打印出这些单词,如果没有wordlist []中的单词可用,那么它应该打印"No Match Found".
这是我的代码我很震惊.请
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
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要使用matches条件input.matches(".*\\b"+wordlist[i]+"\\b.*")
.* :匹配任何东西
\\b:字边界避免匹配four与fourteen
并且wordlist[i]是你的话
1.)使用循环遍历您的数组
2.)从阵列接字,并使用matches具有给定正则表达式来避免匹配four与fourteen
String wordlist[]={"one","two","three","four","five"};
String input="I have three no, fourteen strings";
int i;
boolean found=false;
// Traverse your array
for(i=0; i<wordlist.length;i++){
// match your regex containing words from array against input
if(input.matches(".*\\b"+wordlist[i]+"\\b.*")){
// set found = true
found=true;
// display found matches
System.out.println(wordlist[i]);
}
}
// if found is false here then mean there was no match
if (!found) {
System.out.println("No Match Found");
}
Run Code Online (Sandbox Code Playgroud)
输出:
three
Run Code Online (Sandbox Code Playgroud)