Search code examples
regexrobotframework

Based on the output to get value with regular expression


There's an output like this:

RA#show segment-routing traffic-eng on-demand color detail | utility egrep Color -B 10
Sat Dec 25 11:24:22.891 JST

SR-TE On-Demand-Color database
------------------------

On-Demand Color: 20
--
 Performance-measurement:
   Reverse-path Label: Not Configured
   Delay-measurement: Disabled
   Liveness-detection: Enabled 《-------
     Profile: liveness1
     Invalidation Action: down
     Logging:
       Session State Change: Yes
 Per-flow Information:
  Default Forward Class: 0
On-Demand Color: 23
--
 Performance-measurement:
   Reverse-path Label: Not Configured
   Delay-measurement: Disabled
   Liveness-detection: Enabled  《--------
     Profile: liveness1
     Invalidation Action: down
     Logging:
       Session State Change: Yes
 Per-flow Information:
  Default Forward Class: 0
On-Demand Color: 301

regex "On-Demand Color:\s(\S+)" can be used to extract color "20,23,301", but as Liveness-detection was not enabled under "On-Demand Color: 301", So I expected only color "20" and "23" can be extacted. Is it possible to achieve this by regular expression?


Solution

  • If you want to be a bit more flexible and if the value can be present after n number of lines instead of exactly 5, you can make use of a negative lookahead.

    This will also prevent overmatching if Liveness-detection: Enabled is not present in the current On-Demand Color: part.

    On-Demand Color:\s(\S+)(?:\n(?!On-Demand Color:|\s*Liveness-detection:).*)*\n\s*Liveness-detection: Enabled
    

    The pattern matches:

    • On-Demand Color: Match the starting string
    • \s(\S+) Match a whitespace char and capture 1+ non whitespace chars (or use (\d+)for digits) in capture group 1
    • (?: Non capture group
      • \n(?!On-Demand Color:|\s*Liveness-detection:)
      • .* Match the whole line
    • )* Close non capture group and optionally repeat
    • \n\s*Liveness-detection: Enabled Match a newline, optional whitespace chars and the string that you want to match

    Regex demo