what im trying to do here is to sort the regex findings(for example if they was numbers). im not to sure how to go about doing this, any ideas?
NodeList abcList = firstElement.getElementsByTagName("target");
Element abcElement =(Element)abcList.item(0);
NodeList textAbcList = abcElement.getChildNodes();
String abc = (textAbcList.item(0).getNodeValue().trim());
Pattern pattern = Pattern.compile("Some Regex");
Matcher matcher = pattern.matcher(abc);
while (matcher.find()){
out.write(" abc: " + matcher.group());
}
Finding
To sort results you need to find them all first. You can produce any partial sorted list if you don’t know all the results beforehand. So you’ll have something like:
Note that I’m converting the found string directly to Integer because it has more meaning as an Integer. If by any reason you want to have a string, ok, have a
List<String>and don’t convert.Sorting
After you have a non-sorted list, you need to sort it. There are several methods and Java implements one very easy method. It can do sorting of any type because it doesn’t do the compare between two items. This is the only part that needs to be implemented to define HOW to sort. And you’ll do:
This method will implement mergesort (if I’m not mistaken) and ask the comparator you provide each time it needs to compare two elements. This comparator should implement interface
Comparator<T>whereTis the type of elements in result.If they are integers, you don’t need a comparator because it has already a “natural” order:
But if you want some special ordering (like ordering strings according to its integer represented value) then you can use your own comparator:
compare must return:
As we want to compare strings as if they are numbers, that’s what I did: convert them to numbers and compare their numerical value.
Sorting your strigs: xxx-nnnn-nnnn
In your case you are collecting strings with that format (abc-1234-5678) and you need to sort them according to the first number. So let’s assume you’ve already collected your strings in:
Then you need to sort that strings according to some arbitrary criteria. As usual you’ll need to call
Collections.sortproviding a special comparator.That comparator will need to compare not the whole string, but the first number from each string. By example:
abc-1234-5678anddef-3456-1988. You have to compare1234with3456.Then the code will look something like:
Which regex
I should use:
That finds:
But if you’r not sure of finding the numbers on the second place I should go for: