我想分割一个在${和}之间的字符串

2024-05-08 00:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取限定在${}之间的字符串

示例:

/one/${two}
/${three}/one/${four}
/five/${six}/seven

我有一个代码,它从json字符串读取内容,除了API端点什么都没有。在这个过程中,我想提取${&;之间的单词或字符串}并将它们存储在变量中

下面是从json文件读取数据内容的相同代码

with open("example.json", "r") as reading:
    data = json.load(reading)
    for path, values in data['paths'].items():
        print(path.replace('{', '${'))  # If required used print statement
        for value in values:
            print(value)

输出:

two
three
four
six

Tags: path字符串代码json内容fordataone
1条回答
网友
1楼 · 发布于 2024-05-08 00:33:48

我们可以在这里尝试使用re.findall,模式为\$\{(.*?)\}

input = "/${three}/one/${four}"
matches = re.findall(r'\$\{(.*?)\}', input)
print(matches)

这张照片:

['three', 'four']

相关问题 更多 >