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

How to individually match all numbers that immediately follow a keyword?

我有这个字符串:

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

使用 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 

模式:/(?:\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中看到官方的术语解释link,但这里是我的解释方式...

(?:         # 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 之后遇到 | ("space and pipe") 时停止,因为它们与 \d+ ("space and digits") 不匹配。