寻找
排序,你需要找到他们第一个成果。如果您事先不知道所有结果,则可以生成任何部分排序列表。所以你必须是这样的:
List<Integer> results = new ArrayList<Integer>();
while (there are more results) { // here you ask the regex if it found some more item
// add integer to results
String found = ... // here you grab the string you've just found
results.add(Integer.parseInt(found)); // convert the string to integer and add to list
}
请注意,我找到的字符串直接转换成整数,因为它有更多的含义为整数。如果由于任何原因你想要一个字符串,好吧,有一个List<String>
,不要转换。
排序
之后,你有一个非排序列表,你需要对它进行排序。有几种方法和Java实现一个非常简单的方法。它可以对任何类型进行排序,因为它不会对两个项目进行比较。这是定义如何分类的唯一部分。你会做:
Collections.sort(results, comparator);
这种方法将实现合并排序(如果我没有记错),并要求你每次需要比较两个元素时提供的比较。这个比较器应该实现接口Comparator<T>
其中T
是在结果元素的类型。
如果它们是整数,你并不需要一个比较,因为它已经“自然”的顺序:
Collections.sort(results);
但是,如果你按照它的整数值表示想要一些特殊的排序(如订购串),那么你可以使用自己的比较:
Collections.sort(results, new Comparator<String>() {
public int compare(String a, String b) {
int valueA = Integer.parseInt(a);
int valueB = Integer.parseInt(b);
return valueA - valueB;
}
});
比较必须返回:
- negat ive if < b
- 0 if a == b
- and positive if a> b。
因为我们想比较字符串,就好像它们是数字一样,这就是我所做的:将它们转换为数字并比较它们的数值。
排序您strigs:XXX-NNNN-NNNN
在你的情况,你正在收集的字符串与格式(ABC-1234-5678),你需要根据第一个数字对它们进行排序。因此,让我们假设你已经收集到您的字符串:
List<String> results
然后,你需要的是,根据一些任意的标准字符串进行排序。像往常一样,你需要调用Collections.sort
提供一个特殊的比较。
比较器将不需要比较整个字符串,而是比较每个字符串的第一个数字。例如:abc-1234-5678
和def-3456-1988
。您必须将1234
与3456
进行比较。
然后代码看起来类似:
Collections.sort(results, new Comparator<String>() {
public int compare(String str1, String str2) {
// obtain the number you'll use to compare
int value1 = getImportantNumber(str1);
int value2 = getImportantNumber(str2);
// return comparator (remember, the sign of the results says if it's <, =, >)
return value1 - value2;
}
// this method will extract the number, maybe you'll need a regex or substring, dunno
private int getImportantNumber(String str) {
// by example
Matcher m = PATTERN.matcher(str);
if (!m.find())
return -1; // or throw an exception, depends on you're requirements
String numberPart = m.group(...); // the number of the group catching the part you need
return Integer.parseInt(numberPart);
}
private static Pattern PATTERN = Pattern.compile("....");
});
其中正则表达式
我应该使用:
(\w+)-(\d+)(-(\d+))*
即发现:
letters-numbers[-numbers[-numbers...]]
但如果找你不知道在第二个地方我应该去寻找数字:
String[] parts = str.split("-");
for (String part: parts)
if (this part has only numbers)
return Integer.parseInt(part);
// if there are no only number parts
throw new RuntimeException("Not valid number part found!");
让我明白了:你想好歹排序(从正则表达式搜索)发现的一个列表?在这种情况下,存在两个截然不同的问题:查找和排序。你首先需要列出所有结果。然后分类。请澄清你需要什么,然后我们可以回答不同的问题... – helios
Im解析XML和回顾数字。我需要对这些数字进行排序。 – user1646537
好的。请记住,XML解析器将更好地解析XML。如果你的XML中有一些非xml文本并且需要解析,那么RegEx会很好。 – helios