我正在尝试使用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
您可以将
string
模式声明为为了确保空白,
\s*
匹配0个或多个空白,\s+
匹配1个或多个空白,然后像这样使用它注意,这里,
(?m)^{}$
将锚定string
模式以匹配整行:(?m)
使^
匹配行开始而不是字符串开始,$
匹配行结束而不是字符串结束。你知道吗thing.read()
部分将确保实际将整个文件内容传递给regex引擎,而不是文件句柄。你知道吗相关问题 更多 >
编程相关推荐