英文:
How do I match elements of an array to a given string using regex?
问题
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].contains(needles[i])) {
countArray[i]++;
}
}
}
for (int j = 0; j < needles.length; j++) {
System.out.println(needles[j] + ": " + countArray[j]);
}
}
}
}
英文:
I have this Java code method which compares the elements of an array of strings with a string variable. This method requires two argument: an argument of type string haystack
and an array of strings needles
. If the length of the needles array is greater than 5, it outputs an error message to the console. Otherwise it tries to match the elements of haystack
with needles
using regex. My code returns this:
abc: 0
def: 0
cal: 1
ghi: 0
c: 0
What changes do I need to make so that it matches both cal
and c
. That is the matching works for multiple character elements as well as well as single character elements?
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]);
}
}
}
}
答案1
得分: 1
你可以直接在 haystack 上使用 contains 方法。在你的第一个 for 循环中,使用类似这样的语句:
if (haystack.contains(needles[i]))
做一些操作
这里实际上不需要正则表达式。
英文:
You can use the contains method directly on the haystack. In your first for loop use something like:
if(haystack.contains(needles[i])
doSomething
You dont really need regex here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论