2017-04-14 72 views
0

我有以下代码返回一些json。我想将输出更改为.sub.example.com。通常我可以在awk中做到这一点,但在这种特殊情况下,它需要在python中处理。Python字符串替换

我一直在试图做的是替换文字字符串'example.com',但'sub.example.com'。过滤出IP位的作品,但我无法弄清楚应该是比较容易的部分:(。

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" 
    ] 
+0

你应该在正则表达式中逃避'.'。 – Barmar

+0

没有're.recompile'函数。 – Barmar

+3

你永远不会调用're.sub()' – Barmar

回答

0

filterSub()应该叫re.sub()并返回结果。还需要在正则表达式逃脱. ,因为它具有特殊的意义和使用$锚,所以你只能在网域名称的结尾匹配它

def filterSub(fullList2): 
    return re.sub(r'example\.com$', 'sub.example.com', fullList2) 
0

没有理由使用正则表达式是:。这是一个简单的字符串替换

def filterSub(fullList2): 
    return fullList2.replace("example.com", "sub.example.com") 
+0

我的问题似乎是它并不是我正在使用的字符串。这是词典条目。 –