【发布时间】:2018-07-30 14:32:24
【问题描述】:
我需要在 python 中获取括号 { text } 之间的文本。
这是我的示例字符串,
my_txt = "/home/admin/test_dir/SAM_8860-fg_frame_{001,002,003,004,005,007}.png"
我需要 {} 之间的数字。
我试过了,
>>> re.search(r'{.*}',my_txt).group()
'{001,002,003,004,005,007}'
但它返回字符串和花括号。
预期输出是,'001,002,003,004,005,007'
如何在 python 正则表达式中省略花括号来获取字符串?
【问题讨论】:
-
re.search(r'{(.*?)}',my_txt).group(1) -
re.search(r'{.*}',my_txt).group().replace('{', '').replace('}', '') -
看起来您正在尝试扩展大括号中的内容,就像 bash 一样。如果是这样的话,there exists a package for that
-
使用lookbehind和lookahead:
re.findall('(?<={).+?(?=})',my_txt) -
@WiktorStribiżew 感谢您的评论,它按预期工作。并感谢您的反对
标签: python regex string curly-braces