我有以下正则表达式数组:
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/