-1

I'm trying to store a set of strings in a form of a list with the capability of supporting regular expressions and delete those strings from a file.

For example:

list = ['enabled','vs-index \d+']
  • where 'vs-index \d' is expressed as an regex. (it can be .... vs-index 30, vs-index 40 . etc...)

I have a text file:

config.txt

ltm virtual testing { destination 80.80.80.80:https ip-protocol tcp mask 255.255.255.255 pool pool1 profiles { http { } tcp { } } source 0.0.0.0/0 source-address-translation { type automap } translate-address enabled translate-port enabled vs-index 38 }
ltm virtual blah { destination 50.50.50.50:https mask 255.255.255.255 profiles { fastL4 { } } source 0.0.0.0/0 translate-address enabled translate-port enabled vs-index 35 }

Expected output would be:

ltm virtual testing { destination 80.80.80.80:https ip-protocol tcp mask 255.255.255.255 pool pool1 profiles { http { } tcp { } } source 0.0.0.0/0 source-address-translation { type automap } translate-address enabled translate-port }
ltm virtual blah { destination 50.50.50.50:https mask 255.255.255.255 profiles { fastL4 { } } source 0.0.0.0/0 translate-address enabled translate-port }

The replace() function doesn't accept a list but rather a string. Any way possible to support a list and regex?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    if you want to remove `vs-index 38`, it should be `vs-index \d+`. Otherwise it will just match `vs-index 3` and leave `8`. – Barmar Nov 18 '20 at 19:59

1 Answers1

0

Convert your list to a regexp that matches all the elements, and then use re.sub() to delete all the matches.

import re

l = ['enabled','vs-index \d+']
regex = re.compile('|'.join(l)) # 'enabled|vs-index d+'
with open("config.txt") as f:
    contents = f.read()
result = re.sub(regex, '', contents)
print(result)
Barmar
  • 741,623
  • 53
  • 500
  • 612