'Use Regex to find all occurrences of a specific string and pair it with subsequent occurrences of another string

right now I have a test.txt file that im reading in. it has several new line characters so I am using re.DOTALL. How can I combine subsequent patterns into pairs?

test.txt:

      blah blah blah||| blah blah|| 
                Key_one1_end  ||   blah blah
                blah blah || blah
blah blah |||||| blah blah Value_number : 10
      blah blah blah||| blah blah|| 
                Key_two2_end  ||   blah blah
                blah blah || blah
                      Value_number : f

This is my code

f = open(r'path/to/file/test.txt')
list= re.findall('(Key_\w*_end)|(Value_number...\w*)', f.read(), re.DOTALL)
print (list)
output: [('Key_one1_end', ''), ('', 'Value_number : 10'), ('Key_two2_end', ''), ('', 'Value_number : f')]

I want the output to look like this [('Key_one1_end','Value_number : 10'), ('Key_two2_end', 'Value_number : f')]

any suggestions?



Solution 1:[1]

My plan here is to capture the output given from the above and run another set of commands based on the output i.e. LRR or LGG

You're almost doing exactly that. You could indeed try:

- name: do something if 'LGG' in previous output
  win_shell: dir
  when: "'LGG' in actualpath.stdout"

But of course, the value of actualpath depends on the output given. You can see the result of the command on the console if you configure:

- debug:
    msg: "{{ actualpath }}"

How to make sure i only get whatever i am printing

See my example above.

How to trim the value and save it in the register?

You do not need to. This is 'system' language, instead of 'human' language. It sounds like you want to make it 'pretty'.

Here are some examples which you can definitely use.

If you expect the output of actualpath to be a directory, e.g. C:\somewhere\something, then you should edit the win_shell command to ensure the output of Ansible actually outputs that value. Right now it is simply a long string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin C