![](/img/trans.png)
[英]RegExp: Remove last period in string that can contain other periods (dig output)
[英]Python - Replace parenthesis with periods and remove first and last period
我正在尝试使用包含子域/域分隔符的DNS查找列表的输入文件,其中字符串长度在括号中而不是句点。 它看起来像这样:
(8)subdomain(5)domain(3)com(0)
(8)subdomain(5)domain(3)com(0)
(8)subdomain(5)domain(3)com(0)
我想用句点替换括号和数字,然后删除第一个和最后一个句点。 我的代码目前正在执行此操作,但最后一段时间。 任何帮助表示赞赏。 这是代码:
import re
file = open('test.txt', 'rb')
writer = open('outfile.txt', 'wb')
for line in file:
newline1 = re.sub(r"\(\d+\)",".",line)
if newline1.startswith('.'):
newline1 = newline1[1:-1]
writer.write(newline1)
您可以使用\\(\\d+\\)
正则表达式拆分行,然后加入.
在两端剥去逗号:
for line in file:
res =".".join(re.split(r'\(\d+\)', line))
writer.write(res.strip('.'))
请参阅IDEONE演示
鉴于你的re.sub
调用是这样的:
> re.sub(r"\(\d+\)",".", "(8)subdomain(5)domain(3)com(0)")
'.subdomain.domain.com.'
您唯一需要做的就是从任何前导和尾随中删除结果字符串.
:
> s = re.sub(r"\(\d+\)",".", "(8)subdomain(5)domain(3)com(0)")
> s.strip(".")
'subdomain.domain.com'
全面解决方案:
for line in file:
newline1 = re.sub(r"\(\d+\)",".",line).strip(".")
writer.write(newline1)
import re
def repl(matchobj):
if matchobj.group(1):
return "."
else:
return ""
x="(8)subdomain(5)domain(3)com(0)"
print re.sub(r"^\(\d+\)|((?<!^)\(\d+\))(?!$)|\(\d+\)$",repl,x)
输出: subdomain.domain.com
。
您可以定义自己的replace
功能。
import re
for line in file:
line = re.sub(r'\(\d\)','.',line)
line = line.strip('.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.