Return regular expression value

1

I have the following string:

[11:36:19] Touched down at -56 fpm, gear lever: down, pitch: 3, roll: level, 116 kts

And I'm trying a regular expression to get the value 116 kts, and the string does not have a fixed number of words.

My expression is this:

\[([0-9:]+)\] Touched down at -[0-9]+ fpm, gear lever: down, pitch: 3, roll: level, [0-9]+ kts/

However, pitch and roll values do not always appear, and this generates the error.

    
asked by anonymous 11.10.2017 / 04:54

1 answer

2

You do not need to specify the entire line in the expression if you want the value of "kts", the expression ([0-9]+) kts (one or more numbers followed by "kts") is sufficient for this line. In PHP, use the preg_match function and pass an array to serve as an output:

$linha = '[11:36:19] Touched down at -56 fpm, gear lever: down, pitch: 3, roll: level, 116 kts';
$saida = array();
preg_match('/([0-9]+) kts/', $linha, $saida);
echo $saida[1];

116

All values marked with parentheses in the regular expression (the so-called "catch group", or rematch ) will be returned in the array. The $saida[0] item always contains the text that matches the whole expression. So, you can populate a single array with all the data you want to extract:

$linha = '[11:36:19] Touched down at -56 fpm, gear lever: down, pitch: 3, roll: level, 116 kts';
$saida = array();
preg_match('/\[([0-9:]+)\] .* ([-+0-9]+) fpm, gear lever: ([a-z]+), pitch: ([0-9]+), roll: ([a-z]+), ([0-9]+) kts/', $linha, $saida);
print_r($saida);

Array
(
    [0] => [11:36:19] Touched down at -56 fpm, gear lever: down, pitch: 3, roll: level, 116 kts
    [1] => 11:36:19
    [2] => -56
    [3] => down
    [4] => 3
    [5] => level
    [6] => 116
)

PHP example in repl.it: link

Example of the second regular expression in regex101: link

    
11.10.2017 / 05:19