Re: how to compare two version strings in java
Stefan Ram wrote:
anywherenotes@gmail.com writes:
Is there a good way of doing it?
When the version numbers are limited to 4 positions,
with values ranging from 0 to 99 for each:
public class Main
{
public static long value( final java.lang.String string )
{ if( string.contains( "." ))
{ final int index = string.lastIndexOf( "." );
return value( string.substring( 0, index ))* 100 +
value( string.substring( index + 1 )); }
else return java.lang.Long.valueOf( string ); }
public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ java.lang.System.out.println
( value( "10.1.2.0" ) > value( "9.0.0.0" )); }}
Otherwise, I would parse them into separate parts and
then put those parts into a comparable tuple:
http://www.purl.org/stefan_ram/html/ram.jar/de/dclj/ram/type/tuple/ComparableTuple.html
This allows for an arbitrary number of positions each
of an arbitrary size.
Unfortunately, it reports value("2.0") < value("1.5.1") ...
There's no universally-agreed syntax for version strings. I'm
composing this message on Thunderbird "2.0.0.16", my Java version
is "1.6.0_07" (also known as "1.6.0_07-b06"), I use an O/S whose
version is "5.10" and whose kernel patch level is "Generic_127127-11".
I see no solution for the O.P. other than to know things about the
syntax of the version strings he's interested in, to parse them
into their constituent pieces, and to compare piece by piece. The
java.util.regex package may be helpful for the parsing, but I know
of no way to write a "universal" regex for all styles of versioning.
--
Eric.Sosman@sun.com