The Stupid Engineer The Stupid Engineer - 1 year ago 65
Python Question

Specify variable as a value for starts with regex operator '^'

Is it possible to specify a variable string as input for the '^' when writing a regex?

So if you have the following list of strings:

testlist = ['access-list something something', 'something access-list']

There is a line of code that works when called like this:

NAT_acls = parse.find_objects(r^'access-list')

This code parses a configuration file and returns all the strings that begin with "access-list".

I want to use a variable string that is checked when the above line is called, so only access lists with a specific name are returned. So I can do something like this:

acl_name = ''.join(['access-list',' ',some_acl_name])
NAT_acls = parse.find_objects(^acl_name)

This code doesn't work. Is there a way to use the "^" operator with a variable? I've looked at the documentation, but I'm none the wiser.

Answer Source

The code you seek is

NAT_acls = parse.find_objects(r"^{}".format(re.escape(acl_name)))

The r"^{}" will be populated with the escaped acl_name string. If it contains special regex metacharacters, the results you get with the regex might be not what you expect (as . matches any character but a newline, + matches 1 or more occurrences of the quantified subpattern, etc.).

The ^ will have the regex engine look for a match at the start of the string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download