简体   繁体   中英

Java equivalent for PHP preg_grep

Could somebody tell me if a Java equivalent exist for PHP preg_grep() ? Or supply me with a good way to accomplish the same?

I need to do string matching against element in input array and return array with input array's indexes as preg_grep() does.

There is no exact equivalent. But you can use the String#matches(String) function to test if a string matches a given pattern. For example:

String s = "stackoverflow";
s.matches("stack.*flow");   // <- true
s.matches("rack.*blow");    // <- false

If you want a result array with the matching indices, you can loop over your given input array of strings, check for a match and add the current index of the loop to your result array.

You could use this kind of function, using String.matches() and iterating over your array :

public static List<Integer> preg_grep(String pattern, List<String> array) 
{
    List<Integer> indexes = new ArrayList<Integer>();

    int index = 0;
    for (String item : array) {
        if (item.matches("ba.*")) {
            indexes.add(index);
        }
        ++index;
    }

    return indexes;
}

Ideone Example

How about something like:

private static String[] filterArrayElem(String[] inputArray) {
    Pattern pattern = Pattern.compile("(^a.*)");

    List<String> resultList = new ArrayList<>();
    for (String inputStr : inputArray) {
        Matcher m = pattern.matcher(inputStr);
        if (m.find()) {
            resultList.add(m.group(0));
        }
    }
    return resultList.toArray(new String[0]);
}

You can then use it in the following way:

    String [] input = { "apple", "banana", "apricot"};
    String [] result = filterArrayElem(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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