2024-05-17 07:00:30 发布
网友
因此,作为应用程序的一部分,我需要它从文本文件中读取数据,并在花括号之间获取元素。
例如:
Server_1 {/directory1 /directory2}Server_2 {/directory1/directory2}
Server_1 {
/directory1 /directory2
}
Server_2 {
/directory1
/directory2
然后,如果Server == Server_1,打印目录。
Server == Server_1
谨致问候
迈克尔
你可以试试这个:
\{(.*?)\}
Explanation
\{ 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))
Run the code here
你可以试试这个:
Explanation
\{ matches the character { literally (case sensitive)
(.*?) 1st Capturing Group
.*?
匹配任何字符*?
量词-在零次和无限次之间匹配,尽可能少地匹配,根据需要扩展(惰性)\}
逐字匹配字符}
(区分大小写)提取花括号内内容的示例代码:
Run the code here
相关问题 更多 >
编程相关推荐