从输入字符串中的数组中搜索关键字并打印它们

时间:2017-02-22 13:45:01

标签: java regex string search string-search

我差不多几天都这样做但仍无法获得所需的输出。 好吧,我有一个阵列说  wordlist[]={"One","Two","Three","Four","Five"}; 然后我接受用户的输入。

String input="I have three no, four strings";

现在我要做的是对字符串执行搜索操作以检查数组wordlist []中可用的单词; 与上面的示例类似,输入字符串包含数组中存在的单词three和four。 因此它应该能够从字符串中可用的数组中打印出这些单词,如果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
                }
            }
        }


    }
}

2 个答案:

答案 0 :(得分:5)

您需要使用条件matches

input.matches(".*\\b"+wordlist[i]+"\\b.*")

.*:匹配任何内容

\\b:字边界,以避免fourfourteen匹配

wordlist[i]是你的话

1。)使用循环

遍历数组

2。)从数组中选取单词并使用给定正则表达式的matches以避免fourfourteen匹配

    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");
    }

输出:

three

答案 1 :(得分:1)

使用Java8 Streams,您可以:

 ...
 import java.util.Arrays;
 import java.util.stream.Collectors;
 ...

 String wordlist[]={"one","two","three","four","five"};
 String input=cin.readLine();
 String foundStrings = 
       Arrays.stream(wordlist)
       .filter(s->input.matches(".*\\b"+s+"\\b.*"))
       .collect(Collectors.joining("\n"));

 System.out.print(foundStrings.isEmpty() ? "No Match Found\n": foundStrings);