Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检测所有未用大括号括起的模板表达式_Python_Regex_Regex Lookarounds - Fatal编程技术网

Python 检测所有未用大括号括起的模板表达式

Python 检测所有未用大括号括起的模板表达式,python,regex,regex-lookarounds,Python,Regex,Regex Lookarounds,我有一个模板字符串,如下所示: '%album\u Artister%/%album%{(%year%)}/{%track\u number%.}%track\u Artister%-%title%' 我想找到所有变量,这些变量不是可选的,因此没有用大括号括起来:track\u artist,title,album\u artist和album但不是track\u number和year 目前,我的表达式是”(?re) 相关问题: 如果使用PHP,可以使用以下模式: ~{[^}]*+}(

我有一个模板字符串,如下所示:

'%album\u Artister%/%album%{(%year%)}/{%track\u number%.}%track\u Artister%-%title%'

我想找到所有变量,这些变量不是可选的,因此没有用大括号括起来:
track\u artist
title
album\u artist
album
但不是
track\u number
year

目前,我的表达式是
”(?re

相关问题:


如果使用PHP,可以使用以下模式:

~{[^}]*+}(*SKIP)(*FAIL)|%\w++%~i
例如:

preg_match_all('~{[^}]*+}(*SKIP)(*FAIL)|%\w++%~i', $string, $matches);
print_r($matches);
如果您使用Python,您可以使用捕获组执行相同的操作(即:在搜索之前匹配花括号中的内容,然后搜索您要搜索的内容):

import re

mystr = r'%album_artist%/%album%{ (%year%)}/{%track_number%. }%track_artist% - %title%';
print filter(bool, re.findall(r'{[^}]*|(?i)%(\w+)%', mystr))
注意:

您可以尝试另一种模式,该模式将在开头的花括号后的最后一个
%
处停止匹配(不确定它是否比第一个快):


您可以尝试使用替代选项,仅对不匹配大括号的分支进行分组。它将返回结果,其中包含可以过滤掉的空白字符串,如:

>>> import re
>>> s = r'''%album_artist%/%album%{ (%year%)}/{%track_number%. }%track_artist% - %title%'''
>>> list(filter(lambda e: e.strip(), re.findall(r'\{[^}]*\}|%([^%]*)%', s)))
['album_artist', 'album', 'track_artist', 'title']

您使用的是什么风格/语言?这是什么
(*SKIP)(*FAIL)
构造?我从未见过,RegexBuddy 4也不知道它。@TimPietzcker:啊哈!这是PCRE功能。这些动词是为回溯控制而设计的。SKIP表示前面的子模式无法成功,而失败会迫使子模式失败(如
(?!)
)。目标是避免出现与
\K
不同的空结果。遗憾的是,Python
re
不太支持PCRE。@moi:我添加了一个Python版本。感谢Python版本!如果多个变量用大括号括起来,第二个版本就不起作用,如
str='%album\u artist%/%album%{(%year%)}/{%track\u number%.}{%track\u artist%-%title%}
它可以工作,谢谢!但是,像Casimirs的答案一样使用
filter(bool…)
会更短。
>>> import re
>>> s = r'''%album_artist%/%album%{ (%year%)}/{%track_number%. }%track_artist% - %title%'''
>>> list(filter(lambda e: e.strip(), re.findall(r'\{[^}]*\}|%([^%]*)%', s)))
['album_artist', 'album', 'track_artist', 'title']