PYTHON - Capture contents inside curly braces

后端 未结 2 1747
北海茫月
北海茫月 2020-12-03 18:43

So, as part of my application, i need it to read data from a text file, and get elements between curly brackets.

e.g:

Server_1 {

相关标签:
2条回答
  • 2020-12-03 18:58

    You can try with this:

    \{(.*?)\}
    

    Explanation

    1. \{ matches the character { literally (case sensitive)
    2. (.*?) 1st Capturing Group
    3. .*? matches any character
    4. *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
    5. \} matches the character } literally (case sensitive)

    Sample Code to extract content inside curly bracket:

     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

    0 讨论(0)
  • 2020-12-03 19:11

    If you also want to extract the server name, you can try with this:

    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)
    
    0 讨论(0)
提交回复
热议问题