Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract digits and dots from a string

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.

like image 764
Ran Avatar asked Jan 22 '26 01:01

Ran


2 Answers

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

Allow the .x to repeat and it should work.

like image 121
dee-see Avatar answered Jan 23 '26 15:01

dee-see


Try this one:

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

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

like image 27
Arnaud Le Blanc Avatar answered Jan 23 '26 13:01

Arnaud Le Blanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!