1

I have some many files each file has a set of lines in a given pattern. I want to match those multiple lines at once and do some operations on them such as delete, move to another file etc.

the multiple lines in a file are as given below.

self.unsupported_cmds = [r'\s*clns\s+routing',

                         r'\s*bfd\s+graceful-restart',

                         r'\s*ip\s+default-network',

                         r'\s*ip\s+default-gateway',

                         r'\s*ip\s+subnet-zero',

                         r'\s*ip\s+cef\s*$' ]

The lines within square brackets may vary.

Help me how to do it.

1
  • Please add four leading spaces for all the code. Formatting is a bit complicated to understand now. Commented Dec 16, 2011 at 6:13

1 Answer 1

1

As python re module documentation says you may add the MULTILINE flag to re.compile method. This will let you match entire file at once.

import re

regex = re.match(r'''(
    ^\s*clns\s+routing$ |
    ^\s*bfd\s+graceful-restart$ |
    ^\s*ip\s+default-network$ |
    ^\s*ip\s+default-gateway$ |
    ^\s*ip\s+subnet-zero$ |
    ^\s*ip\s+cef\s*$
)+''', re.MULTILINE | re.VERBOSE)

Notice that I've added VERBOSE flag to write regex with additional formatting to make regex look nicer. Also you should see that there are several ^ and $ symbols. That is how multiline regex allows you to match over multiple lines in one file.

Additionally I must warn you that this regex will only help to match file just to be sure is entire file correctly formatted. If you want to parse data from this file you need to modify this regex a little to satisfy your needs.

Second code variant

import re

regex = re.match(r'''(^
    \s*
    (clns|bfd|ip)
    \s+
    (routing|graceful-restart|default-network|default-gateway|subnet-zero|cef)
$)+''', re.MULTILINE | re.VERBOSE)
Sign up to request clarification or add additional context in comments.

7 Comments

Could you please provide me the regular expression to match above set of lines?
This is cool, but the lines with in the brackets many vary. Can you provide me a better solution?
@ameet what you mean under word "vary"? I've added + that was missed. Now this regex will match any file that consists of the lines you've provided in any order.
@ameet, you could use '|'.join(list_of_regexps) every time list_of_regexps changes.
@ameet I've added second regex variant to let you additional example for better understanding. The second variant let you match the strings that consist of the any combination of the positional words from your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.