简体   繁体   English

与{{string | trans}}匹配的正则表达式

[英]Regex that matches {{ string|trans }}

I have multiple .phtml files and I would like to select all the strings before |trans }}, without {{ before the string. 我有多个.phtml文件,我想选择| trans}}之前的所有字符串,而在字符串前没有{{。

Like this: 像这样:

{% block title %}{{ 'Detail Hostess:'|trans }} {{ host.Name }}{% endblock %}

Now I would like to select 'Detail Hostess:' . 现在,我想选择'Detail Hostess:' This is the regex that I have now: 这是我现在拥有的正则表达式:

/\{{2}\s*([^|]+)\|trans\s*\}{2}/i

Sometimes it works, but in the case above he selects 'Detail Hostess:' and 有时它可行,但在上述情况下,他选择了'Detail Hostess:'
host.Name }}{% endblock %} {% block content

So how can I fix the regex? 那么我该如何修复正则表达式呢?

Your issue might be linked to the fact that when you use [^|]+ , there's nothing to prevent you from going outside of a {{...}} construct: your regex will match host.Name }}{{ 'Detail Hostess:' in {{ host.Name }}{{ 'Detail Hostess:'|trans }} . 您的问题可能与以下事实有关:使用[^|]+ ,没有什么可以阻止您脱离{{...}}构造:您的正则表达式将匹配host.Name }}{{ 'Detail Hostess:'{{ host.Name }}{{ 'Detail Hostess:'|trans }}

If you're sure there can be no } in your wanted text, a quick fix would be replacing [^|] with [^|}] : 如果您确定想要的文本中没有} ,那么一个快速解决方案是将[^|]替换为[^|}]

{{\s*([^|}]+)\|trans\s*}}

Btw in PHP no need to escape the { if it's not followed by a digit, nor } if not preceded by one: see demo . 顺便说一句,PHP中的Btw不需要转义{如果后面没有数字,或者}如果前面没有数字:请参见demo

I think that having the "|trans" mark, there is no need to check for "|" 我认为带有“ | trans”标记的无需检查“ |” or "}", you just have to look for "|trans", but using a lazy quantifier. 或“}”,您只需要查找“ | trans”即可,但要使用惰性量词。

/{{\s*(.+?)\|trans\s*}}/i

Test: http://www.phpliveregex.com/p/4Ly 测试: http//www.phpliveregex.com/p/4Ly


Edit. 编辑。 Correction fixing what Casimir et Hippolyte says. 更正卡西米尔和希波吕特所说的内容。

The advantage of this solution is that there are not forbidden characters inside the searched string. 该解决方案的优点是在搜索的字符串中没有禁止的字符。

Robin 's answer may be faster, but the searched string cannot contain "|" Robin的答案可能更快,但搜索的字符串不能包含“ |” or "}" characters. 或“}”字符。

Thanks at @Robin. 感谢@Robin。 This is the expression I'm finally using to parse translation filters in Twig: 这是我最终用来解析Twig中的翻译过滤器的表达式:

{{([^}]+)\|(?:transchoice\((.*?)\)|transchoice|trans|trans\((.*?)\))(?:\|([^}]+)|\s*)}}

this RegEx covers: 此正则表达式涵盖:

{{ 'foo'|trans }}
{{ 'foo %variable%'|trans({'%variable%':'foo'}) }}
{{ 'foo'|humanize|trans }}
{{ 'foo %variable%'|trans({'%variable%':'foo'})|capitalize }}

and also all variants with transchoice . 以及所有具有transchoice变种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM