1

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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • You can take a look at http://stackoverflow.com/questions/5084419/java-preg-match-array – Simon Jul 17 '14 at 15:35
  • For future reference, questions about regexes should be tagged [tag:regex] in addition to the language/flavor tags ([tag:java], [tag:php], etc.). The [tag:qregularexpression] tag refers to a specific implementation, which you are not using. – Alan Moore Jul 22 '14 at 01:10

3 Answers3

1

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.

Jack
  • 2,937
  • 5
  • 34
  • 44
1

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

zessx
  • 68,042
  • 28
  • 135
  • 158
  • Thanks, I think this should do my job. I am new to java, I have to port my php project to java in order to automate running of script. since I am new to java, i will have to take some time to test your solution. – user3127090 Jul 17 '14 at 15:55
1

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);
Venkat Rangan
  • 385
  • 1
  • 2
  • 7