Reputation: 391
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.
Upvotes: 3
Views: 6580
Reputation: 99921
Try this one:
'/\d+(\.\d+)+/'
The difference with yours is that it allows the .\d+
part to repeat, thus allowing multiple dots.
Upvotes: 2
Reputation: 714
To match software version numbers with one/without/multiple dots one could use:
\d+(?:\.*\d*)*
(kudos to authors before this post)
Upvotes: 0
Reputation: 24088
if (preg_match('/\d+(?:\.\d+)+/', $version, $matches)) {
return $matches[0]; //returning the first match
}
Allow the .x
to repeat and it should work.
Upvotes: 11