Reputation: 1238
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!
Upvotes: 2
Views: 1218
Reputation: 44289
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:
"(?<!\()#{to_wrap}(?!\))"
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):
"(?<![(])#{to_wrap}(?![)])"
Upvotes: 3