用正则表达式匹配字符串数组内容

问题描述 投票:0回答:2

我是Java的新手。我正在尝试使用Java正则表达式比较两个包含名称的字符串数组,然后使用嵌套的for循环打印出具有匹配项的名称和不具有匹配项的名称。下面是我的代码

public class Main {

    public static void main(String[] args) {

    // write your code here
        String regex;
        Pattern pattern;
        String stringToBeMatched;
        Matcher matcher;
        boolean b;
     String [] names1 = {"Peter","Harry","Potter","Mary","Jerry"};
        String [] names2 = {"Adam","Jerry","Potter","Martin","Chris", "Rose"};
        //try a loop with two variables for loop

                for (int x=0;x >= names2.length;x++) {
                     regex = names2[x];
                     pattern = Pattern.compile(regex);

                    for(int y = 0; y >= names1.length; y++){
                        stringToBeMatched = names1[y];
                        matcher = pattern.matcher(stringToBeMatched);
                        b = matcher.find();

                        if (b) {System.out.println(names1[y] +" has a match");}
                        else{System.out.println(names1[y] +" has no match");}
                    }
                }
    }
}

代码执行并返回输出Process finished with exit code 0,而不显示任何System.out.println()语句指定的任何消息。拜托,我在做什么不对?

java regex nested-loops string-matching
2个回答
0
投票

除非我误解了您的意图,否则您不应在此处使用正则表达式。我的理解是,您想比较两个数组中重复的元素。

您有自己的数组:

String[] names1 = {"Peter", "Harry", "Potter", "Mary", "Jerry"};
String[] names2 = {"Adam", "Jerry", "Potter", "Martin", "Chris", "Rose"};

方法1-嵌套循环。

for(int i = 0; i < names1.length; i++) {
  for(int j = 0; j < names2.length; j++) {
    if(names1[i].equals(names2[j])) System.out.println(names1[i] + " is in both arrays.");
  }
}

方法2-嵌套的foreach循环。

for(String name1 : names1) {
  for(String name2 : names2) {
    if(name1.equals(name2)) System.out.println(name1 + " is in both arrays.");
  }
}

方法3-使用List

List<String> names2List = Arrays.asList(names2);

for(String name1 : names1) {
  if(names2List.contains(name1)) System.out.println(name1 + " is in both arrays.");
}

方法4-使用Set。之所以有效,是因为HashSet#add()不会添加重复项,如果需要,则返回false。

Set<String> names2Set = new HashSet<>(Arrays.asList(names2));

for(String name1 : names1) {
  if(!names2Set.add(name1)) System.out.println(name1 + " is in both arrays.");
}

方法5-使用Streams。如果您想花哨。

for(String name1 : names1) {
  if(Arrays.stream(names2).anyMatch(name1::equals)) System.out.println(name1 + " is in both arrays.");
}

0
投票

对于lambda函数,请使用“ distinct”来不打印重复值。

© www.soinside.com 2019 - 2024. All rights reserved.