PYTHON-捕获大括号内的内容 [英] PYTHON - Capture contents inside curly braces

查看:760
本文介绍了PYTHON-捕获大括号内的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

服务器_1 {

Server_1 {

/directory1/directory2

/directory1 /directory2

}

服务器_2 {

/directory1

/directory1

/directory2

/directory2

}

然后类似,如果是Server == Server_1,则打印目录.

Then something like, if Server == Server_1, print the directories.

亲切的问候,

迈克尔

推荐答案

您可以尝试以下操作:

\{(.*?)\}

说明

  1. \{ matches the character { literally (case sensitive)
  2. (.*?) 1st Capturing Group
  3. .*?匹配任何字符
  4. *?量词-匹配零次至无限次,次数尽可能少,根据需要扩展(延迟)
  5. \}从字面上匹配字符}(区分大小写)
  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))

在此处运行代码

这篇关于PYTHON-捕获大括号内的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆