简体   繁体   English

如何检查字符串是否包含搜索项

[英]How to check whether a string contains the search items

I have a String and a String[] filled with search items. 我有一个String和一个充满搜索项的String[]

How can I check whether my String contains all of the search items? 如何检查我的String是否包含所有搜索项?

Here is an example: 这是一个例子:

Case 1: 情况1:

String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "test";

Case 2: 情况2:

String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "tes";

In case 1, the method should return true , but in case 2 the method should return false . 在情况1中,该方法应返回true ,但在情况2中,该方法应返回false

You can do this using word boundaries in regex: 您可以使用正则表达式中的单词边界来执行此操作:

boolean result = true;
for (String item : searchItems) {
    String pattern = ".*\\b" + item + "\\b.*";
    // by using the &&, result will be true only if text matches all patterns.
    result = result && text.matches(pattern);
}

The boundaries ensure that the search terms will only be matched if the whole word is present in your text. 边界确保仅当整个单词都出现在您的文本中时,搜索词才会匹配。 So, "tes" will not match against "test" because "\\btes\\b" is not a substring of "\\btest\\b" . 所以, "tes"将不匹配对"test" ,因为"\\btes\\b"是不是一个字符串"\\btest\\b"

I would try to split the string with spaces and then loop thought all the splinted parts. 我会尝试用空格分割字符串,然后循环考虑所有夹板部分。

Something like this for your code to work: 这样的代码可以正常工作:

String text = "this is a stupid test";
List<String> searchItems = new ArrayList<String>();
searchItems.add("stupid");
searchItems.add("test");
for(String word : test.split(" ")) {
   if(searchItems.contains(word)){
      //do your stuff when the condition is true ...
   } else {
      //do your stuff when the condition is false ...
   }
}

I would make an array of all words in the text. 我会在文本中排列所有单词的数组。 Then check it with 2 for loops if the textArray contains all the searchterms. 然后,如果textArray包含所有搜索项,请使用2进行循环检查。

public boolean search(String text, String[] searchItems) {

    String[] textArray = text.split(" ");

    for(String searchitem: searchItems) {

       boolean b = false;

       for(String word : textArray) {

           if(word.equals(searchitem)) {
               b = true;
               break;
           }

        }

     // text doesn't contain searchitem
     if(!b) return false;

     }

     return true;

}
text.matches(".*\\b" + searchItems[0] + "\\b.*")

注意: "\\\\b"将确保仅匹配“整个单词”。

public boolean findIfAllItemsMatch(String[] searchItems, String text) {
    boolean allItemsMatch = true;
    for (String item_ : searchItems) {
        if(!text.contains(item_)) {  
              allItemsMatch = false;
              break;
         }
    }
    return allItemsMatch;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM