在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/