开发者

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 mat开发者_Go百科ch 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.


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

Allow the .x to repeat and it should work.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜