【发布时间】:2021-09-09 21:24:05
【问题描述】:
我有一个巨大的文本文件,其中包含以这种格式存储的信息。
someOtherMessage{
class = "someClass";
sampleMessage{
someValue{
someText{
someParam = "value";
someSymbol = "another_symbol";
}; //someText
}; //someValue
}; //sampleMessage
}; //someOtherMessage
someOtherMessage2{
class = "someClass2";
sampleMessage2{
someValue2{
someText2{
someParam = "value2";
someSymbol = "another_symbol2";
}; //someText2
}; //someValue2
}; //sampleMessage2
}; //someOtherMessage2
我想使用 py 脚本遍历这个文件,并以以下格式构建一个 dict(或任何其他数据结构)。
例如。
dict = {'someOtherMessage': 'someOtherMessage{
class = "someClass";
sampleMessage{
someValue{
someText{
someParam = "value";
someSymbol = "another_symbol";
}; //someText
}; //someValue
}; //sampleMessage
}; //someOtherMessage',
'someOtherMessage2': 'someOtherMessage2{
class = "someClass2";
sampleMessage2{
someValue2{
someText2{
someParam = "value2";
someSymbol = "another_symbol2";
}; //someText2
}; //someValue2
}; //sampleMessage2
}; //someOtherMessage2'
}
我使用了以下正则表达式,但它选择了第一个和最后一个花括号之间的所有内容,我怎样才能让它分别选择所需的?
【问题讨论】:
-
会不会一直有那个'}; //someOtherMessage
\nsomeOtherMessage2{' 你想要的任意两部分之间的新行? -
@AKSingh,是的,实际上也可以有多个新行!
-
(?s)\{(.*?)\};.*?(\n\n|$)在^和$不 匹配每一行的结尾处试试这个。简单来说,不要加m修饰符。 -
@AKSingh,检查this。
-
请删除
m修饰符。试试regex101.com/r/1T7Bey/1。
标签: python regex string file-handling string-matching