匹配并删除fi中的字符串

2024-03-29 08:58:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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

Tags: inpyremastercomzonestringbind
1条回答
网友
1楼 · 发布于 2024-03-29 08:58:41

您可以将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)使^匹配行开始而不是字符串开始,$匹配行结束而不是字符串结束。你知道吗

thing.read()部分将确保实际将整个文件内容传递给regex引擎,而不是文件句柄。你知道吗

相关问题 更多 >