正则表达式在字符串上获取版本

时间:2018-05-05 06:03:55

标签: php regex

我想查询Minecraft服务器并获取他们的版本。但是当我查询服务器时,在版本中我得到字符串:

BotFilter 1.8.x-1.12.x => I need get 1.12
BotFilter 1.8.x-1.12.x by hek.com Leymooo_s => I need get 1.12
Spigot 1.8.8 => I need get 1.8
Spigot 1.8.9 => I need get 1.8.9
BungeeCord 1.10-1.12x => I need get 1.12
Spigot 1.5.2 => I need 1.5.2
1.8.8 (Spigot) => I need get 1.8
1.9.2 Vanilla => 1.9
CraftBukkit 1.7.2 => I need get 1.7.2
BungeByGame 1.x-1.12.2 => I need get 1.12.2
Requires MC 1.8/1.9/1.10/1.11/1.12 => I need get 1.12
1.8.8 (CraftBukkit on Bukkit 1.8.8-R0.1-SNAPSHOT) => 1.8.8

我有正则表达式:

$version = '1.8.8 (Spigot)';

preg_match('~^.*[ -]\K\d+(?:\.\d+)*~m', $version, $result);

但是不使用变量$version中的字符串..也许还有其他字符串..

1 个答案:

答案 0 :(得分:1)

更新

使用负面的lookbehind确保数字后面没有版本字符或英文字母:

^.*\K\d(?<![a-z\d.].)\d*(?:\.\d+)*+

Live demo

PHP代码(see demo):

$version = '1.8.8 (CraftBukkit on Bukkit 1.8.8-R0.1-SNAPSHOT)';
preg_match('~^.*\K\d(?<![a-z\d.].)\d*(?:\.\d+)*+~mi', $version, $result);
print_r($result[0]); // 1.8.8