The regex
command uses a java.util.Pattern
to match the input from the previous command. The regex
will match if the pattern is any part of the input (Pattern.find
in java).
We have to explicitly use ^
and $
to target the beginning, end, or entire input.
- sh: cat server.log
- regex: "started in (?<seconds>\\d+\\.\\d{3}) seconds
- log: seconds = ${{seconds}}
The pattern’s named capture groups are added to the script’s state
and are available to
subsequent commands. It is a good idea to put commands that use the capture groups under
then
so that they are only invoked if the pattern matched. We can use else
to invoke commands
if the pattern does not match.
- sh: cat server.log
- regex: "started in (?<seconds>\\d+\\.\\d{3}) seconds
then:
- log: seconds = ${{seconds}}
else:
- abort: failed to start
The named capture groups can use the state RUN.
and HOST.
prefixes target global run state
or the host state instead of the default script state. This lets other scripts access the values but will
likely require coordination to ensure the value is ready before other scripts try to access it.
scripts:
getTime:
- sh: cat server.log
- regex: "started in (?<RUN.seconds>\\d+\\.\\d{3}) seconds
useTime:
- log: seconds = ${{seconds}} #will find the RUN.seconds from getTime
We can also use the java embedded flag expressions to change how the patterns match the input. Notably we can use (?s)
to use the DOT_ALL
mode so that .
will match newlines.
The regex
command finds the first match for the pattern. It does not find all the places where the pattern could match. Therefore a pattern with a capture group will only capture the first occurance. If you want to match each occurance you can use regex
in a watch
to observe the command line by line or use parse
to extract a json structure with the target pattern.