Java 正则表达式 : Check in specific order

标签 java regex

我有以下正则表达式数组:

String[] array = new String[] { 
  "(car)|(truck)|(bus)|(van)", //4) transportation
  "(w)|(x)|(y)|(z)", //1) options
    "1|2|3|4", //2) numbers
    "(red)|(blue)|(green)|(pink)|(yellow)" //3) color
};

我有以下字符串:

String s= "1 blue w truck";

我试图迭代该字符串以查看字符串中的任何单词是否与数组中的任何正则表达式匹配。这就是我正在做的事情:

for(int i=0; i<array.length;i++){
      Pattern word = Pattern.compile(array[i]);
      Matcher match = word.matcher(s);
      while(match.find() ){
        System.out.println(String.format(" Using regex %d:  %s",i,match.group()));
      }
    }

这给出了以下输出:

Using regex 0:  truck
Using regex 1:  w
Using regex 2:  1
Using regex 3:  blue

但我希望输出如下:

Using regex 2:  1
Using regex 3:  blue
Using regex 1:  w
Using regex 0:  truck

我希望字符串中的单词保持相同的顺序,而不更改数组中正则表达式的顺序。

最佳答案

这是一个使用 pojo 的解决方案,其中包含匹配项的相关信息(此处任意称为 MatchInfo),以及一个 TreeSet 按所需标准对匹配项进行排序(给定String内匹配的索引)。

// your patterns
String[] array = new String[] { 
    "(car)|(truck)|(bus)|(van)", // 4) // transportation
    "(w)|(x)|(y)|(z)", // 1) options
    "1|2|3|4", // 2) numbers
    "(red)|(blue)|(green)|(pink)|(yellow)" // 3) color
};
// your input
String s = "1 blue w truck";

// the definition of the relevant information you want to keep on matches
class MatchInfo implements Comparable<MatchInfo>{
    int index;
    Integer start;
    String match;
    MatchInfo(int index, int start, String match) {
        this.index = index;
        this.start = start;
        this.match = match;
    }
    @Override
    // comparing start index of the match within original string
    public int compareTo(MatchInfo o) {
        return start.compareTo(o.start);
    };
}
// orders unique elements by natural ordering, as defined by Comparable 
// implementation
Set<MatchInfo> groups = new TreeSet<>();

// your original iteration
for (int i = 0; i < array.length; i++) {
    Pattern word = Pattern.compile(array[i]);
    Matcher match = word.matcher(s);
    while (match.find()) {
        // adding new "MatchInfo" to the set
        groups.add(new MatchInfo(i, match.start(), match.group()));
    }
}

// iterating and printing the info
for (MatchInfo m: groups) {
    System.out.printf("Using regex %d: %s%n", m.index, m.match);
}

输出

Using regex 2: 1
Using regex 3: blue
Using regex 1: w
Using regex 0: truck

关于Java 正则表达式 : Check in specific order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37029046/

相关文章:

java - 了解为什么 Java 模式与缓冲的 .java 文件中的不正确文本相匹配?

java - 合规级别是否足以在 Java 6 上运行?

javascript - 如何用 javascript 中以特殊字符开头的单词内的空格替换下划线?

java - 使用 Java 泛型从类名获取类型

JAVA-空指针异常

python - 基于 url 的正则表达式前瞻

ruby - 如何在 ruby​​ 中将括号与正则表达式匹配

php - bbcode 解析器正则表达式帮助

java - 防止对 java servlet 的重复请求

java - 最有效地从文件中写入和读取 LocalDateTime