I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working.
List<String> sp = Arrays.asList(splited);
int i2 = sp.indexOf("^w.*$");
indexOf
doesn't accept a regex, you should iterate on the list and use Matcher
and Pattern
to achieve that:
Pattern pattern = Pattern.compile("^w.*$");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.print(matcher.start());
}
Maybe I misunderstood your question. If you want to find the index in the list of the first string that begins with "w", then my answer is irrelevant. You should iterate on the list, check if the string startsWith
that string, and then return its index.
The
indexOf
method doesn't accept a regex pattern. Instead you could do a method like this:And then you simply could write: