java - 数组上的正则表达式匹配 (Java)

标签 java regex arrays function

在Java中,我有一个String[]文件路径。我需要一个函数来获取 String[]返回,其中包含与指定正则表达式匹配的所有字符串。

Java 有内置函数吗?还是我必须自己做?

最佳答案

您必须执行循环并逐个字符串检查

public static void main(String args[]) {
    String[] a = {"1", "a", "b" };
    List<String> b = new ArrayList<String>();
    for (int i=0; i<a.length; i++) {
        if (a[i].matches("(a|b)")) { // matches uses regex
            System.out.println("Match " + a[i]);
            b.add(a[i]);
        }
    }
}

给乞丐点赞:

public static void main(String args[]) {
    String[] a = {"1", "a", "b" };
    String [] res;
    List<String> b = new ArrayList<String>();
    Pattern p = Pattern.compile("(a|b)");
    Matcher m;
    for (int i=0; i<a.length; i++) {
        m = p.matcher(a[i]);
        if (m.matches()) {
            System.out.println("Match " + a[i]);
            b.add(a[i]);
        }
    }
    res = (String[]) b.toArray();
}

更清洁:

private static String[] getMatches(String[] strings) {
    Pattern p = Pattern.compile("(a|b)");
    List<String> matches = new ArrayList<String>();

    for (String s : strings) {
        if (p.matcher(s).matches()) {
            matches.add(s);
        }
    }

    return (String[]) matches.toArray();
}

关于java - 数组上的正则表达式匹配 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14218412/

相关文章:

c - 无法为数组赋值

java - 如何关闭 ExecutorService?

java - 字符串的正则表达式包含不在特定集合中的字符

java - 在这种情况下我将如何正确使用数组?

无法将数组值带入函数

php - 用 preg_match() 匹配括号

java - 出现错误页面,上周上传文件有效,但我没有做任何更改

java - jar 文件更改时 spring boot 热重载

regex - 如何在第三个字符后插入连字符

Python 正则表达式仅查找两位数字