I’m trying to wrap parentheses around string in ruby, only if it isn’t wrapped yet:
"my string (to_wrap)" => "my string (to_wrap)"
"my string to_wrap" => "my string (to_wrap)"
I’ve tried something like:
to_wrap = 'to_wrap'
regexp = Regexp.new "(?!\()#{to_wrap}(?!\))"
string.sub(regexp, "(#{to_wrap})")
but it does not work.
Thanks in advance!
You are very close. Your first negative lookaround is a lookahead, though. So it looks at the first character of
to_wrap. Just make that a lookbehind:And just to present you with an alternative option to escape parentheses (it’s really a matter of taste which on to use, but I find it more easily readable):