如何使用正则表达式将数组元素与给定字符串匹配?
How do I match elements of an array to a given string using regex?
我有这个 Java 代码方法,它将字符串数组的元素与字符串变量进行比较。此方法需要两个参数:一个字符串类型参数 haystack
和一个字符串数组 needles
。如果 needles 数组的长度大于 5,它会向控制台输出一条错误消息。否则它会尝试使用正则表达式将 haystack
的元素与 needles
匹配。我的代码 returns 这个:
abc: 0
def: 0
cal: 1
ghi: 0
c: 0
我需要进行哪些更改才能使其与 cal
和 c
匹配。那是对多个字符元素以及单个字符元素的匹配?
public class Needles {
public static void main(String[] args) {
String[] needles = new String[]{"abc", "def", "cal", "ghi", "c"};
findNeedles("cal'", needles);
}
public static void findNeedles(String haystack, String[]
needles) {
if (needles.length > 5) {
System.err.println("Too many words!");
} else {
int[] countArray = new int[needles.length];
String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);
//String[] words = haystack.split("", 0);
for (int i = 0; i < needles.length; i++) {
for (int j = 0; j < words.length; j++) {
if (words[j].compareTo(needles[i]) == 0) {
countArray[i]++;
}
}
}
for (int j = 0; j < needles.length; j++) {
System.out.println(needles[j] + ": " + countArray[j]);
}
}
}
}
你可以直接在大海捞针上使用contains方法。在你的第一个 for 循环中使用类似的东西:
if(haystack.contains(needles[i])
doSomething
这里你真的不需要正则表达式。
我有这个 Java 代码方法,它将字符串数组的元素与字符串变量进行比较。此方法需要两个参数:一个字符串类型参数 haystack
和一个字符串数组 needles
。如果 needles 数组的长度大于 5,它会向控制台输出一条错误消息。否则它会尝试使用正则表达式将 haystack
的元素与 needles
匹配。我的代码 returns 这个:
abc: 0
def: 0
cal: 1
ghi: 0
c: 0
我需要进行哪些更改才能使其与 cal
和 c
匹配。那是对多个字符元素以及单个字符元素的匹配?
public class Needles {
public static void main(String[] args) {
String[] needles = new String[]{"abc", "def", "cal", "ghi", "c"};
findNeedles("cal'", needles);
}
public static void findNeedles(String haystack, String[]
needles) {
if (needles.length > 5) {
System.err.println("Too many words!");
} else {
int[] countArray = new int[needles.length];
String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);
//String[] words = haystack.split("", 0);
for (int i = 0; i < needles.length; i++) {
for (int j = 0; j < words.length; j++) {
if (words[j].compareTo(needles[i]) == 0) {
countArray[i]++;
}
}
}
for (int j = 0; j < needles.length; j++) {
System.out.println(needles[j] + ": " + countArray[j]);
}
}
}
}
你可以直接在大海捞针上使用contains方法。在你的第一个 for 循环中使用类似的东西:
if(haystack.contains(needles[i])
doSomething
这里你真的不需要正则表达式。