匹配并删除文件中的字符串

时间:2018-09-12 23:17:42

标签: python regex

我当前正在尝试使用re搜索该文件并删除区域

//
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";
zone "domain.com" {
        type master;
        file "/etc/bind/zones/domain.com.signed";
        allow-transfer { 1.2.3.4; };

 };
zone "4.3.2.in-addr.arpa" {
        type master;
        file "/etc/bind/rev.domain.com";
        allow-transfer { 1.2.3.4; };
 };

zone "example.com" {
        type master;
        file "/etc/bind/zones/example.com";
};

目前我有这个

import re

string = 'zone "example.com" { type master; file "/etc/bind/zones/example.com";};'
with open('zone.conf.local') as thing:
    re.sub(r'^%s$' % string, '', thing)

但是当我尝试运行它时,出现此错误

Traceback (most recent call last):
  File "zone.py", line 5, in <module>
    re.sub(r'^%s$' % string, '', thing)
  File "/home/john/.virtualenvs/hw/lib/python3.6/re.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

我认为也许我不应该在re的模式中添加字符串,但是当我尝试这样做时

import re

string = 'zone "example.com" { type master; file "/etc/bind/zones/example.com";};'
with open('zone.conf.local') as thing:
    re.sub('^$', string, '', thing)

这仍然行不通并输出

Traceback (most recent call last):
  File "zone.py", line 5, in <module>
    re.sub('^$', string, '', thing)
  File "/home/john/.virtualenvs/hw/lib/python3.6/re.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: '_io.TextIOWrapper' object cannot be interpreted as an integer

1 个答案:

答案 0 :(得分:2)

您可以将string模式声明为

string = r'zone\s*"example.com"\s*{\s*type\s*master;\s+file\s+"/etc/bind/zones/example.com";\s*};'

为确保空格,\s*匹配0个或多个空格,\s+匹配1个或多个空格,然后像使用

new_contents = re.sub(r'(?m)^{}$'.format(string), '', thing.read())

请注意,这里(?m)^{}$将锚定string模式以匹配整行:(?m)启用^来匹配行开始而不是字符串开始,而{{1 }}以匹配行尾而不是字符串尾。

$部分将确保您确实将整个文件内容传递给了regex引擎,而不是文件句柄。