Ruby regex匹配双唇髭,但不是三八字。

时间:2021-08-04 14:26:58

I am using mustache gem in my ruby on rails app. Given a template, I would like to replace all double mustache in the template with triple mustache, and not replace when it is a triple mustache. There won't be single mustache in the original template, so i don't want to worry about single mustache.

我正在我的ruby on rails应用程序中使用mustache gem。如果有一个模板,我希望将模板中的所有双胡子替换为三重胡子,而不要替换为三重胡子。原来的模板不会有单唇髭,所以我不想担心单唇髭。

Eg:

例如:

temp = "You have just won {{value}} {{{currency}}}!"

should convert to

应该转换为

temp = "You have just won {{{value}}} {{{currency}}}!"

1 个解决方案

#1


3  

This could be done via a negative lookahead.

这可以通过一个消极的展望来完成。

\{\{[^}]+\}\}(?!\})

This will match substrings enclosed by 2 mustaches, but not followed by a third.

这将匹配包含2个八字胡的子字符串,但后面没有第三个。

The matches can then be enclosed with extra mustaches.

然后,比赛可以加上额外的小胡子。

temp = "You have just won {{value}} {{{currency}}}!"
temp.gsub!(/\{\{[^}]+\}\}(?!\})/, '{\&}')
puts temp

#1


3  

This could be done via a negative lookahead.

这可以通过一个消极的展望来完成。

\{\{[^}]+\}\}(?!\})

This will match substrings enclosed by 2 mustaches, but not followed by a third.

这将匹配包含2个八字胡的子字符串,但后面没有第三个。

The matches can then be enclosed with extra mustaches.

然后,比赛可以加上额外的小胡子。

temp = "You have just won {{value}} {{{currency}}}!"
temp.gsub!(/\{\{[^}]+\}\}(?!\})/, '{\&}')
puts temp