繁体   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