簡體   English   中英

如何使用正則表達式將數組元素與給定字符串匹配?

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

我有這個 Java 代碼方法,它將字符串數組的元素與字符串變量進行比較。 此方法需要兩個參數:字符串型的參數haystack和字符串數組needles 如果needles數組的長度大於5,則向控制台輸出錯誤信息。 否則,它會嘗試使用正則表達式將haystack的元素與needles進行匹配。 我的代碼返回這個:

abc: 0
def: 0
cal: 1
ghi: 0
c: 0

我需要進行哪些更改才能使其同時匹配calc 那是匹配適用於多個字符元素以及單個字符元素嗎?

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

    }

  }
}

你可以直接在 haystack 上使用 contains 方法。 在你的第一個 for 循環中使用類似的東西:

if(haystack.contains(needles[i])
     doSomething

你在這里真的不需要正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM