Search code examples
rubyregexlookbehind

Ruby regex that matches unless escaped with \


To identify things like:

[stack][overflow]
or
[is great!]

I do:

/\[([^\]]+)\](\[([^\]]+)\])?/.match(s)

Now I want to extend this such that if [...][...] or [...] comes after \ it won't be recognized:

\[stack][overflow]   # => Should not match
\[is great!]         # => Should not match
a \[b][c] \[d] [e]   # => Should match [e]

How could I extend the regex to achieve this ?

It should work both in Ruby 1.9.2 and Ruby 1.8.7.


Solution

  • I came up with this regexp:

    /([^\\\[\]]|^)\[([^\]]+)\](\[([^\]]+)\])?/
    

    You can try it here:

    http://rubular.com/r/L796M2pcG7

    Hope that helps.

    EDIT: reacted to your comment EDIT: next one