Re: sorting strings with embedder digits



Nigel Wade wrote:
On Fri, 27 Nov 2009 16:08:32 +0000, tony wrote:

On Fri, 27 Nov 2009 14:02:23 +0000, Bent C Dalager wrote:

On 2009-11-26, tony <tony@xxxxxxxxxxxxxxxxx> wrote:
Currently I need to sort a list of filenames such as 'track 11.mp3',
'track 4.mp3'. My problem is that a simple sort will put track 11
first because it's alphabetical. My approach seems tortuous - split
around any digits, then from there build an array holding each part in
turn. Once that is done, you can compare the array entries and where
digits are involved, compare them numerically.

Does anyone know of a neater way to do this?
I wrote something like this once, I have put it here:
http://www.pvv.org/~bcd/StringNumberComparator.java

Cheers,
Bent D
I'd actually got as far as using a custom comparator. I didn't want to
assume that the initial text was the same in each case, so the approach
was:
1: If there were no digits, just use the String compareTo otherwise 2:
split each string with split("[0-9]") and remove any empty entries. 3:
rebuild the array inserting any digit sequences by finding their
position, extracting them and putting hem in the right place 4: Compare
the matching array elements until a decision could be made. The digit
strings are identified and compared by parsing as integers.

There were a few hiccups but it seems to work. I've modified it
slightly to have one for files using filenames as well.

Tony

I would have thought it would be much simpler and easier to use a regular expression and a match group. Something like:

Pattern p = Pattern.compile(".*?(\\d+).*");
Matcher m = p.matcher(yourString);
if ( m.matches() ) {
// The Pattern matched yourString, and contains a set of digits.
// m.group(1) should contain the matched string of digits.
}

You can tweak the RE to get a more accurate match if it's not exactly as required for your string contents.

"file12.ver3"
"file12.ver10"

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.


Quantcast