【问题标题】:Get element starting with letter from List从List中获取以字母开头的元素
【发布时间】:2015-06-22 09:24:23
【问题描述】:

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

List<String> sp = Arrays.asList(splited);
int i2 = sp.indexOf("^w.*$"); 

【问题讨论】:

  • 这是完整的字符串"^w.*$吗?
  • 看起来您想使用正则表达式。 indexOf 将检查列表中是否有任何字符串等于 "^w.*$",而不是匹配 "^w.*$"

标签: java android list indexof


【解决方案1】:

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.*$");

【讨论】:

    【解决方案2】:

    indexOf 不接受正则表达式,您应该迭代列表并使用 MatcherPattern 来实现:

    Pattern pattern = Pattern.compile("^w.*$");
    Matcher matcher = pattern.matcher(str);
    
    while (matcher.find()) {
        System.out.print(matcher.start());
    }
    

    也许我误解了你的问题。如果您想在以“w”开头的第一个字符串的列表中找到索引,那么我的回答是无关紧要的。你应该对列表进行迭代,检查字符串startsWith是否为那个字符串,然后返回它的索引。

    【讨论】:

    • 是的,我想在第一个以“w”开头的字符串的列表中找到索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2021-10-24
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2020-10-05
    相关资源
    最近更新 更多