从列表中获取以字母开头的元素

Get element starting with letter from List

我有一个列表,我想获取以特定字母开头的字符串的位置。 我正在尝试这段代码,但它不起作用。

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 实现:

Pattern pattern = Pattern.compile("^w.*$");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.print(matcher.start());
}

可能我误解了你的问题。如果你想在第一个以"w"开头的字符串的列表中找到索引,那么我的答案是无关紧要的。您应该遍历列表,检查字符串 startsWith 那个字符串,然后 return 它的索引。

indexOf 方法不接受正则表达式模式。相反,您可以使用如下方法:

public static int indexOfPattern(List<String> list, String regex) {
    Pattern pattern = Pattern.compile(regex);
    for (int i = 0; i < list.size(); i++) {
        String s = list.get(i);
        if (s != null && pattern.matcher(s).matches()) {
            return i;
        }
    }
    return -1;
}

然后你可以简单地写:

int i2 = indexOfPattern(sp, "^w.*$");