捕获花括号内的内容 [英] Capture contents inside curly braces

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

问题描述

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

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

例如:

Server_1 {

    /directory1 /directory2

}

Server_2 {

    /directory1

    /directory2

}

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

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

推荐答案

你可以试试这个:

{(.*?)}

说明

  1. { 匹配字符 { 字面意思(区分大小写)
  2. (.*?) 第一个捕获组
  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 {
"
    "/directory1 /directory2

"
    "}
"
    "Server_2 {

"
    "/directory1

"
    "/directory2

"
    "}")

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

在此处运行代码

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

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