1

This is my output:

CASE 1:
---------------------------------- 
Drop Pack: FALSE 
Drop Flow: FALSE 
---------------------------------- 
CASE 2:
---------------------------------- 
Drop Flow: TRUE 
Fail Open: FALSE 
Fail Close: FALSE 
---------------------------------- 
CASE 3:
---------------------------------- 
Drop Flow: FALSE 

I need a regex to match values as below:

regex 1: to get only the first match as below

 Drop Flow: FALSE (UNDER CASE1)

regex 2: to get only the second match as below:

 Drop Flow: TRUE (UNDER CASE2)

The regex I have is:

Drop Flows:\s+([A-Z]+)

But this gives all the 3 matches (case 1 , case2 and case3). How can I get individual matches?

Thanks in advance

mchapa
  • 63
  • 1
  • 5

2 Answers2

1

Try it as suggested:

(CASE \d+)(?:(?!CASE \d+)[\s\S])*(Drop Flow: (?:TRUE|FALSE))
  • The pattern starts searching the head anchor using CASE \d+ and puts it in $1,
  • consumes everything that does not contain this very string (?:(?!CASE \d+)[\s\S])* to avoid grabbing the Drop Flow value from another CASE,
  • and finally, searches the end anchor (Drop Flow: (?:TRUE|FALSE)) and puts it in $2.

DEMO

Some Python code along that lines:

import re
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1
        print ("Group {groupNum}: {group}".format(groupNum = groupNum, group = match.group(groupNum)))
wp78de
  • 18,207
  • 7
  • 43
  • 71
0

If you only want the first 2 matches and not the third on, you can add a positive lookahead (?=\s*\r?\n\S) that asserts that there should be a line following that starts with a non whitespace char \S

Drop Flow:\s+([A-Z]+)(?=\s*\r?\n\S)

Regex demo

Another option is to capture the value in group 1, and the TRUE FALSE part in group 2 and make sure there is a closing line that starts with a hyphen.

^CASE \d+:\r?\n-+[^\S\r\n]*(?:\r?\n(?!Drop Flow:).*)*\r?\n(Drop Flow: (TRUE|FALSE))[^\S\r\n]*(?:\r?\n(?!-).*)*\r?\n-

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70