Return regular expression value

Asked

Viewed 112 times

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, where the string doesn’t have a fixed word number.

My expression is this:

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

But the pitch and roll values do not always appear, and what generates the error.

  • 1

    And that expression? \d+(?=\s*kts) and the debug of Regex101. Using Positive Lookahead ?=

  • 1

    If the idea is to use Positive Lookahead to see if the numbers \d+ are followed by possible space and the string kts, why not simply \d\s*kts? Not that it’s against the Lookahead, haha, I just think that sometimes it increases the complexity of regex unnecessarily, and it’s not a feature supported everywhere (although in the present case, that is [tag:php], yes). + 1 because showed the Regex101, did not know! = D

1 answer

2

No need to specify the entire line in the expression if you want the value of "kts", the expression ([0-9]+) kts (one or more consecutive numbers of " kts") is enough for that line. In PHP use the function preg_match and pass an array to serve as 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 "capture group", or rematch) will be returned in the array. The item $saida[0] always contains text that matches the whole expression. Thus, it is possible to 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
)

Example of PHP in repl.it: https://repl.it/M0qa/1

Example of the second regular expression in regex101: https://regex101.com/r/ZXMq6Y/1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.