因此,作为我的应用程序的一部分,我需要它从文本文件中读取数据,并在大括号之间获取元素。
e.g:
Server_1 {
/ directory1 / directory2
}
Server_2 {
/ directory1中
/ directory2
}
然后,如果Server == Server_1
,打印目录。
亲切的问候,
迈克尔
答案 0 :(得分:12)
你可以试试这个:
\{(.*?)\}
\{ matches the character { literally (case sensitive)
(.*?) 1st Capturing Group
.*?
匹配任何字符*?
量词 - 零和无限次之间的匹配,尽可能少,根据需要扩展(懒惰)\}
字面匹配字符}
(区分大小写)用于提取大括号内的内容的示例代码:
import re
regex = r"\{(.*?)\}"
test_str = ("Server_1 {\n"
"/directory1 /directory2\n\n"
"}\n"
"Server_2 {\n\n"
"/directory1\n\n"
"/directory2\n\n"
"}")
matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL)
for matchNum, match in enumerate(matches):
for groupNum in range(0, len(match.groups())):
print (match.group(1))
答案 1 :(得分:0)
如果您还想提取服务器名称,则可以尝试以下操作:
fullConfig = """
Server_1 {
/directory1 /directory2
}
Server_2 {
/directory1
/directory2
}
"""
# OUTPUT
# ('Server_1', '/directory1 /directory2\n')
# ('Server_2', '/directory1\n /directory2\n')
regex = r'(\w+)\s*[^{]*{\s*([^}]+)\s*}'
for serverName, serverConfig in re.findall(regex, fullConfig):
print(serverName, serverConfig)