开发者

Regex - How do I get this value from a line of a text file?

开发者 https://www.devze.com 2023-01-31 21:49 出处:网络
I\'m so very poor at preg_match, which I think is the function required here. 开发者_如何转开发I\'m trying to get the time value (always 3 decimals I think) from this line in a text file:-

I'm so very poor at preg_match, which I think is the function required here. 开发者_如何转开发I'm trying to get the time value (always 3 decimals I think) from this line in a text file:-

frame=    42 q= 38.0 f_size=    909 s_size=        1kB time= 1.400 br=   218.2kbits/s avg_br=     5.2kbits/s type= I

So, in that example I want to get 1.400. Any guidance much appreciated, I find regex truly, truly baffling.


Or to get all values at once:

preg_match_all("/(\w+)=\s*(\d[\d.]*)/", $str, $uu);
$values = array_combine($uu[1], $uu[2]);

would give you:

Array
(
  [frame] => 42
  [q] => 38.0
  [f_size] => 909
  [s_size] => 1
  [time] => 1.400
  [br] => 218.2
  [avg_br] => 5.2
)


if(preg_match('/time\s*=\s*(\d+\.\d{3})/',$str,$matches)) {
   $time = $matches[1];
}

Just incase you are not sure about the number of decimal digits or the existence of the decimal point you can do:

if(preg_match('/time\s*=\s*(\d+\.?\d+)/',$str,$matches)) {
   $time = $matches[1];
}

See it


use time=[^\d]*([\d]+\.[\d]+|[\d]+) :

$string1 = "frame=    42 q= 38.0 f_size=    909 s_size=        1kB time= 1.400 br=   218.2kbits/s avg_br=     5.2kbits/s type= ";
$string2 = "frame=    42 q= 38.0 f_size=    909 s_size=        1kB time= 400 br=   218.2kbits/s avg_br=     5.2kbits/s type= ";

preg_match('#time=[^\d]*([\d]+\.[\d]+|[\d]+)#',$string1,$matches1);
preg_match('#time=[^\d]*([\d]+\.[\d]+|[\d]+)#',$string2,$matches2);

print $matches1[1]; // prints 1.400
print $matches2[1]; // prints 400


$match = preg_match('/time=\\s*(\\d+(\\.\\d+)?)/', $row, $matches);

$time = $matches[1];

What this does is match:

  • the literal string time=
  • followed by zero or more spaces ( \s* )
  • followed by one or more digits ( \d+ )
  • followed optionally by: a dot, then one or more digits ( (\.\d+)? )

So it's in fact a little looser than digit-dot-three digits: it will match any integer or floating point number, with any number of decimal digits.

0

精彩评论

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