Thursday, 15 April 2010

ruby on rails - Use Regexp to replace optional match between charaters -



ruby on rails - Use Regexp to replace optional match between charaters -

i'm trying replace html entity blank space actual space between occurrences of {{ , }}

example example

"this     gap {{  for user in users }}" => "this     gap {{ user in users }}"

i've found answers similar had led me write (which doesn't work)

.gsub(/(?<=\{\{).*(&nbsp;?).*(?=\}\})/,' ')

any help such regex appreciated thanks!

single phone call gsub using \k , \g

it's bit tricky, in ruby 2.0+, can compact regex \k , \g tokens. utilize regex , replace space:

[^{}]*\k(?:{{|\g).*?\k&nbsp;(?=[^{]*})

see demo.

in ruby:

result = subject.gsub(/[^{}]*\k(?:{{|\g).*?\k&nbsp;(?=[^{]*})/, ' ')

explanation

[^{}]* matches chars not braces \k tells engine drop matched (?:{{|\g) either matches opening curlies or asserts positioned after lastly match .*?\k lazily matches chars (and drops them), to... &nbsp; our match! which, lookakead (?=[^{]*}) asserts, must followed chars not opening brace before meeting closing brace

ruby-on-rails regex

No comments:

Post a Comment