A given- I’m using Ruby 1.8.7 and therefor can’t use negative lookbehind. I’m also aware of oniguruma but am looking for solutions without it.
If I have:
foo = "string and string [foo and string stuff] string and strings foostring string"
w = "string"
How can I modify this:
foo.gsub(/\b#{w}\b/i) {|s| "[#{w}]"}
So that the ‘string’ enclosed anywhere between [] is not matched, e.g the desired result is:
"[string] and [string] [foo and string stuff] [string] and strings foostring [string]"
Thanks!
If you know that the square brackets will always occur in balanced pairs as they do in your example, you can do a negative lookahead for an unbalanced closing bracket after the word. If the opening bracket isn’t after the word, it must be before the word. Example:
Another option is to match either a pair of brackets and everything inside them, or the target string. If it’s a bracketed sequence you matched, you plug it right back in; otherwise you add brackets to the matched string and plug that in. In this case it’s even simpler: you can just capture everything inside the brackets in one group, or the target string in another group, then use the
\+metasequence to plug in the contents of whichever group matched, with brackets added. Example:see them in action on ideone