如何单独匹配紧跟关键字的所有数字?

时间:2018-01-19 22:19:22

标签: php regex preg-match-all

我有这个字符串:

28.6MH\/s 27.3MH\/s | Temp(C): 64 66 61 64 63 | Fan: 74% 76% 69% 75% 72% | HW: 21 21 21 

我希望提取Temp值,但我无法弄清楚我做错了什么。

我提出的表达方式(并且不起作用)是:

((?<temp>\d\d)(?!\.).+(?!Fan))+

Debuggex Demo

2 个答案:

答案 0 :(得分:1)

使用preg_match()函数和特定的正则表达式模式:

$str = "28.6MH\/s 27.3MH\/s | Temp(C): 64 66 61 64 63 | Fan: 74% 76% 69% 75% 72% | HW: 21 21 21";
preg_match('/(?<=Temp\(C\): )[\s\d]+(?=\| Fan)/', $str, $m);
$temp_values = $m[0];

print_r($temp_values);

输出:

64 66 61 64 63 

答案 1 :(得分:0)

模式:/(?:\G(?!^)|Temp\(C\):) \K\d+/Demo

代码:(Demo

$in='28.6MH\/s 27.3MH\/s | Temp(C): 64 66 61 64 63 | Fan: 74% 76% 69% 75% 72% | HW: 21 21 21 ';

var_export(preg_match_all('/(?:\G(?!^)|Temp\(C\):) \K\d+/',$in,$out)?$out[0]:'fail');

输出:

array (
  0 => '64',
  1 => '66',
  2 => '61',
  3 => '64',
  4 => '63',
)

说明:

您可以在Pattern Demo链接中看到官方术语解释,但这是我的解释方式......

(?:         # start a non-capturing group so that regex understands the piped "alternatives"
\G          # match from the start of the string or where the previous match left off
(?!^)       # ...but not at the start of the string (for your case, this can actually be omitted, but it is a more trustworthy pattern with it included
|           # OR
Temp\(C\):  # literally match Temp(C):
)           # end the non-capturing group
            # <-- there is a blank space there which needs to be matched
\K          # "release" previous matched characters (restart fullstring match)
\d+         # match one or more digits greedily

模式在|之后到达63(“空格和管道”)时停止,因为它们与\d+(“空格和数字”)不匹配。