Search for a regexp in a java arraylist

前端 未结 6 1748
失恋的感觉
失恋的感觉 2020-12-14 19:13
ArrayList  list = new ArrayList(); 
list.add(\"behold\");
list.add(\"bend\");
list.add(\"bet\");
list.add(\"bear\");
list.add(\"beat\");
list.add(\"bec         


        
6条回答
  •  醉梦人生
    2020-12-14 20:03

    Is there a built-in method? Not that I know of. However, it should be rather easy to do it yourself. Here's some completely untested code that should give you the basic idea:

    import java.util.regex.Pattern;
    import java.util.ListIterator;
    import java.util.ArrayList;
    
    /**
     * Finds the index of all entries in the list that matches the regex
     * @param list The list of strings to check
     * @param regex The regular expression to use
     * @return list containing the indexes of all matching entries
     */
    List getMatchingIndexes(List list, String regex) {
      ListIterator li = list.listIterator();
    
      List indexes = new ArrayList();
    
      while(li.hasNext()) {
        int i = li.nextIndex();
        String next = li.next();
        if(Pattern.matches(regex, next)) {
          indexes.add(i);
        }
      }
    
      return indexes;
    }
    

    I might have the usage of Pattern and ListIterator parts a bit wrong (I've never used either), but that should give the basic idea. You could also do a simple for loop instead of the while loop over the iterator.

提交回复
热议问题