Question

I'm using the following code to extract the version number from a string. The version number is the first match made only by digits and dots. For example in the string: "GT-I9000M-user 2.25.31 FROYO UGKC1 release-keys" the match would be: "2.25.31" Another example in string: "1.24.661.1hbootpreupdate:13DelCache: 1" the match would be: "1.24.661.1".

My current code is:

if (preg_match('/[\d]+[\.][\d]+/', $version, $matches)) { 
    return $matches[0]; //returning the first match 
}

This code fits only some of the cases but not all of them. For example in the first example it will only return: "2.25" instead of "2.25.31". In the second example it will return "1.24" instead of "1.24.661.1".

I'm new to RegEx so I'm having a hard time figuring it out.

Thanks for your help.

Was it helpful?

Solution

if (preg_match('/\d+(?:\.\d+)+/', $version, $matches)) { 
    return $matches[0]; //returning the first match 
}

Allow the .x to repeat and it should work.

OTHER TIPS

Try this one:

'/\d+(\.\d+)+/'

The difference with yours is that it allows the .\d+ part to repeat, thus allowing multiple dots.

To match software version numbers with one/without/multiple dots one could use:

\d+(?:\.*\d*)*

(kudos to authors before this post)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top