I have been doing this since almost past few days but still unable to get a required output.
Well I have an array say
wordlist[]={"One","Two","Three","Four","Five"};
and then i take input from the user.
String input="I have three no, four strings";
Now what i want to do is perform a search operation on the string to check for the words available in the array wordlist[]; Like in the above example input string contains the words three and four that are present in the array. so it should be able to print those words from array available in the string, and if no words from the wordlist[] are available then it should print "No Match Found".
Here's My code i'm struck with this. Please
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
}
}
}
}
}
You need to use matches
with condition input.matches(".*\\b"+wordlist[i]+"\\b.*")
.*
: match anything
\\b
: word boundary to avoid matching four
with fourteen
and wordlist[i]
is your word
1.) Traverse your array using loop
2.) Pick words from array and use matches
with given regex to avoid matching four
with 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");
}
Output :
three