我正在扫描一个“.twig”(PHP模板)文件并试图捕获对象的属性名
细枝文件包含如下行(字符串):
{{ product.id }}
{{ product.parentProductId }}
{{ product.countdown.startDate | date('Y/m/d H:i:s') }}
{{ product.countdown.endDate | date('Y/m/d H:i:s') }}
{{ product.countdown.expireDate | date('Y/m/d H:i:s') }}
{{ product.primaryImage.originalUrl }}
{{ product.image(1).originalUrl }}
{{ product.image(1).thumbUrl }}
{{ product.priceWithTax(preferences.default_currency) | money }}
我想捕捉的是:
.id
.parentProductId
.countdown
.startDate
.endDate
.expireDate
.primaryImage
.originalUrl
.image(1)
.originalUrl
.thumbUrl
.priceWithTax(preferences.default_currency)
基本上,我正在尝试找出product
对象的属性。我有以下模式,但它不捕获链接属性。例如
"{{.+?product(\.[a-zA-Z]+(?:\(.+?\)){,1})++.+?}}"
只捕获.startDate
,但它应该分别捕获.countdown
和.startDate
。这是不可能的,还是我遗漏了什么
我可以捕获("{{.+?product((?:\.[a-zA-Z]+(?:\(.+?\)){,1})+).+?}}"
)它作为一个整体(.countdown.startDate
),然后检查/拆分它,但这听起来很麻烦
试试这个,你的需求都能满足
demo and explanation at regex 101
如果您想用一个regex来处理它,您可能需要使用PyPi
regex
模块:参见Python demo
{{[^{}]*product(\.[a-zA-Z]+(?:\([^()]+\))?)*[^{}]*}}
正则表达式将匹配{{
-{{
子串[^{}]*
-0+除{
和}
以外的字符product
-子串product
(\.[a-zA-Z]+(?:\([^()]+\))?)*
-捕获组1:零个或多个\.
-一个点[a-zA-Z]+
-1+ASCII字母(?:\([^()]+\))?
—可选的(
、除(
和)
之外的1+字符序列,然后是)
[^{}]*
-0+除{
和}
以外的字符}}
-a}}
子串李>如果仅限于
re
,则需要将所有属性捕获到一个捕获组中(将此(\.[a-zA-Z]+(?:\([^()]+\))?)*
包装为(...)
),然后运行基于regex的post进程,按.
而不是括号内进行拆分:见this Python demo
我决定坚持
re
(而不是维克托建议的regex
),这就是我最终得到的结果:输出示例:
相关问题 更多 >
编程相关推荐