在 java 数组列表中搜索正则表达式 [英] Search for a regexp in a java arraylist
本文介绍了在 java 数组列表中搜索正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ArrayList <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
有一种方法可以搜索正则表达式 bea.* 并获取 ArrayList.indexOf 中的索引吗?
There is a way to search for the regexp bea.* and get the indexes like in ArrayList.indexOf ?
返回项目很好,但我需要比线性搜索具有更高性能的东西
returning the items is fine but I need something with more performance than a Linear search
推荐答案
Herms 掌握了基本知识.如果您想要字符串而不是索引,那么您可以使用 Java 5 foreach 循环进行改进:
Herms got the basics right. If you want the Strings and not the indexes then you can improve by using the Java 5 foreach loop:
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<String> getMatchingStrings(List<String> list, String regex) {
ArrayList<String> matches = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
for (String s:list) {
if (p.matcher(s).matches()) {
matches.add(s);
}
}
return matches
}
这篇关于在 java 数组列表中搜索正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文