有内置方法吗?从来没听说过。但是,自己做应该很容易。这是一些完全未经测试的代码,应该可以为您提供基本概念:
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<Integer> getMatchingIndexes(List<String> list, String regex) {
ListIterator<String> li = list.listIterator();
List<Integer> indexes = new ArrayList<Integer>();
while(li.hasNext()) {
int i = li.nextIndex();
String next = li.next();
if(Pattern.matches(regex, next)) {
indexes.add(i);
}
}
return indexes;
}
我可能对 Pattern 和 ListIterator 部分的使用有点错误(我从来没有使用过),但这应该给出基本的想法。您还可以在迭代器上执行简单的 for 循环而不是 while 循环。