在Java ArrayList中搜索正则表达式 [英] Search for a regexp in a java arraylist

查看:911
本文介绍了在Java ArrayList中搜索正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ArrayList中搜索正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆