import re
new_value = "'1999-12-31'"
with open("temp.txt") as infile:
data = infile.read()
data = re.split(r"(var beforeDate = new Date\()(.*?)(\))", data)
# data[0] is everything before the first capture
# data[1] is the first capture
# data[2] is the second capture the one we want to replace
data[2] = new_value
with open("output.txt", "w") as outfile:
outfile.write(''.join(stuff))
你可以放弃捕获中间组,但你会在列表中插入内容。换个地方比较容易。你知道吗
奥托,这个问题可能很小,不需要重锤。以下是相同的代码,没有re:
new_value = "'1999-12-31'"
with open("temp.txt") as infile:
data = infile.read()
data = list(data.partition('var beforeDate = new Date('))
data += data.pop().partition(')')
data[2] = new_value
with open("output.txt", "w") as outfile:
for stuff in data:
outfile.write(stuff)
print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('2015-08-21') #date determined by fair die roll
print "Here they are, standing in a row"
你知道吗主.py你知道吗
import re
new_value = "'1999-12-31'"
with open("temp.txt") as infile:
data = infile.read()
data = re.sub(r"(var beforeDate = new Date\().*?(\))", "\\1"+new_value+"\\2", data)
with open("output.txt", "w") as outfile:
outfile.write(data)
你知道吗输出.txt运行后:
print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('1999-12-31') #date determined by fair die roll
print "Here they are, standing in a row"
就我个人而言,我通常重新拆分()使用起来比回复sub(). 这将重用Kevin的代码,并将捕获它所做的一切(加上中间组),然后替换中间组:
你可以放弃捕获中间组,但你会在列表中插入内容。换个地方比较容易。你知道吗
奥托,这个问题可能很小,不需要重锤。以下是相同的代码,没有re:
用正则表达式怎么样?示例:
你知道吗温度.txt你知道吗
你知道吗主.py你知道吗
你知道吗输出.txt运行后:
相关问题 更多 >
编程相关推荐