【发布时间】:2015-10-28 21:08:33
【问题描述】:
我正在读取一个文件并将其内容存储为多行字符串。然后我循环遍历从 django 查询中获得的一些值,以根据查询结果值运行正则表达式。我的正则表达式似乎应该可以工作,如果我复制查询返回的值,它就可以工作,但由于某种原因,当所有部分一起工作时不匹配,这样结束
我的代码是:
with open("/path_to_my_file") as myfile:
data=myfile.read()
#read saved settings then write/overwrite them into the config
items = MyModel.objects.filter(some_id="s100009")
for item in items:
regexString = "^\s*"+item.feature_key+":"
print regexString #to verify its what I want it to be, ie debug
pq = re.compile(regexString, re.M)
if pq.match(data):
#do stuff
所以基本上我的问题是正则表达式不匹配。当我将文件内容复制到一个大的旧字符串中,并复制由print regexString 行打印的值时,它确实匹配,所以我认为有一些深奥的 python/django 事情正在发生(或者可能不是这样深奥,因为 python 不是我的第一语言)。
例如,print regexString 的输出是:
^\s*productDetailOn:
文件内容:
productDetailOn:true,
allOff:false,
trendingWidgetOn:true,
trendingWallOn:true,
searchResultOn:false,
bannersOn:true,
homeWidgetOn:true,
}
运行 Python 2.7。此外,转储了 item.feature 和 data 的类型,并且都是 unicode。不确定这是否重要?无论如何,在工作了几个小时后,我开始从桌子上摔下来,所以任何帮助都表示感谢。干杯!
【问题讨论】:
-
尝试将
r添加到"^\s*":r"^\s*"。 -
@stribizhev 请问r是做什么的?
-
@stribizhev 抱歉,我们匆匆走一走来发泄一下。那么适当的等价物是:
regexString = r"^\s*"+item.feature_key+":"?一定不能因为那不起作用 -
我找到了罪魁祸首:
match
标签: python regex django python-2.7