我有一个形式的字符串
**var beforeDate = new Date('2015-08-21')**
这里我不知道 paranthesis() 之间的值。我想用任何其他日期替换此日期。我怎样才能在 Python 中做到这一点? 我想打开文件,然后使用该语言的标准替换功能,但由于 () 之间的值未知,所以这是不可能的。
这个片段以及这个片段之后会有很多代码,所以用新行替换整行是行不通的,因为它会覆盖这个片段周围的代码。
最佳答案
使用正则表达式怎么样?示例:
临时文件
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"
关于python - 替换周围已知但字符串值未知的字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181489/