PYTHON - 捕捉花括号内的内容

时间:2016-12-05 11:06:12

标签: python regex string parsing text

因此,作为我的应用程序的一部分,我需要它从文本文件中读取数据,并在大括号之间获取元素。

e.g:

  

Server_1 {

     

/ directory1 / directory2

     

}

     

Server_2 {

     

/ directory1中

     

/ directory2

     

}

然后,如果Server == Server_1,打印目录。

亲切的问候,

迈克尔

2 个答案:

答案 0 :(得分:12)

你可以试试这个:

\{(.*?)\}

Explanation

  1. \{ matches the character { literally (case sensitive)
  2. (.*?) 1st Capturing Group
  3. .*?匹配任何字符
  4. *?量词 - 零和无限次之间的匹配,尽可能少,根据需要扩展(懒惰)
  5. \}字面匹配字符}(区分大小写)
  6. 用于提取大括号内的内容的示例代码:

     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))
    

    Run the code here

答案 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)
相关问题