0

I have the following bit of code that returns some json. I want to change the output to be .sub.example.com. Normally I would be able to do this in awk, but in this particular case it needs to be handled in python.

What I've been trying to do is replace the literal string 'example.com' but 'sub.example.com'. The filtering out IP bit works, but I just can't figure out what should be the easier part :(.

def filterIP(fullList):
   regexIP = re.compile(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$')
   return filter(lambda i: not regexIP.search(i), fullList)

def filterSub(fullList2):
   regexSub = re.recompile('example.com', 'sub.example.com', fullList2)

groups = {key : filterSub(filterIP(list(set(items)))) for (key, items) in groups.iteritems() }

print(self.json_format_dict(groups, pretty=True))

  "role_1": [
    "type-1.example.com",
    "type-12-sfsdf-453-2.example.com"
  ]
Brando__
  • 365
  • 6
  • 24

2 Answers2

0

filterSub() should call re.sub() and return the result. You also need to escape . in the regular expression, since it has special meaning. And use the $ anchor so you only match it at the end of the domain name.

def filterSub(fullList2):
    return re.sub(r'example\.com$', 'sub.example.com', fullList2)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

There's no reason to use regex for this: it's a simple string replace.

def filterSub(fullList2):
    return fullList2.replace("example.com", "sub.example.com")
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • My problem seems to be that it's not actually strings that I'm working with. It's dictionary entries. – Brando__ Apr 14 '17 at 20:55