简体   繁体   中英

How do I match elements of an array to a given string using regex?

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]);
      }
      

    }

  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM