0

I'm trying to use regex to find a pattern across a string list:

static List<Integer> getMatchingIndexes(List<String> list, String regex) {
    ListIterator<String> li = list.listIterator();
    List<Integer> indexes = new ArrayList<Integer>();
    System.out.println(list.matches("\\w.*"));
    while(li.hasNext()) {
        int i = li.nextIndex();
        String next = li.next();
        if(Pattern.matches(regex, next)) {
            indexes.add(i);
        }
    }
    System.out.println(indexes);
    return indexes; 
}

It looks like nothing is showing up int he list, when I try to see if there are any matches (list.matches("\w.*")); (just an example, not the actual regex), it keeps giving me an error:

The method matches(String) is undefined for the type List

How can I use regex on this list?

2 Answers 2

2

Iterate through the list (using a for-each loop) and check for matches:

for (String s : list) {
    s.matches("\\w.*");
    // Do stuff here.
}
Sign up to request clarification or add additional context in comments.

1 Comment

@johnc. s is the currently selected String from list as it iterates.
1

Try to iterate through each item in the List<Integer> by the following:

for(Integer i : indexes){
    System.out.println(i.toString().matches("\\w.*"));
}

The above is equivalent to:

for(int i=0; i<indexes.size(); i++){
    System.out.println(indexes.get(i).toString().matches("\\w.*"));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.