gpt4 book ai didi

python 正则表达式不使用 re.match 和 re.MULTILINE 标志匹配文件内容

转载 作者:行者123 更新时间:2023-12-01 04:35:06 25 4
gpt4 key购买 nike

我正在读取一个文件并将其内容存储为多行字符串。然后,我循环遍历从 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。不确定这是否重要?不管怎样,在工作了几个小时后,我开始把头从 table 上抬起来,所以任何帮助都是值得赞赏的。干杯!

最佳答案

根据文档,re.match绝不允许在行的开头进行搜索:

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

您需要使用re.search:

regexString = r"^\s*"+item.feature_key+":"
pq = re.compile(regexString, re.M)
if pq.search(data):

关于原始字符串的小注释 (r"^\s+"):在本例中,它相当于 "\s+" 因为没有 \s 转义序列(如 \r\n),因此,Python 将其视为原始字符串文字。尽管如此,在 Python 中始终使用原始字符串文字(以及其他语言中的相应符号)声明正则表达式模式更安全。

关于python 正则表达式不使用 re.match 和 re.MULTILINE 标志匹配文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com