title: Ruby Regex match unless escaped with \
body: <p>Using Ruby I'm trying to split the following text with a Regex</p>
  
  <pre><code>~foo\~\=bar =cheese~monkey
  </code></pre>
  
  <p>Where ~ or = denotes the beginning of match unless it is escaped with \</p>
  
  <p>So it should match</p>
  
  <pre><code>~foo\~\=bar
  </code></pre>
  
  <p>then</p>
  
  <pre><code>=cheese
  </code></pre>
  
  <p>then</p>
  
  <pre><code>~monkey
  </code></pre>
  
  <p>I thought the following would work, but it doesn't.</p>
  
  <pre><code>([~=]([^~=]|\\=|\\~)+)(.*)
  </code></pre>
  
  <p>What is a better regex expression to use?</p>
  
  <p><strong>edit</strong> To be more specific, the above regex matches all occurrences of = and ~</p>
  
  <p><strong>edit</strong> Working solution. Here is what I came up with to solve the issue.  I found that Ruby 1.8 has look ahead, but doesn't have lookbehind functionality.  So after looking around a bit, I came across <a href="http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/2d510e6db73d1598" rel="nofollow noreferrer">this post</a> in comp.lang.ruby and completed it with the following:</p>
  
  <pre><code># Iterates through the answer clauses
  def split_apart clauses
    reg = Regexp.new('.*?(?:[~=])(?!\\\\)', Regexp::MULTILINE)
  
    # need to use reverse since Ruby 1.8 has look ahead, but not look behind
    matches =  clauses.reverse.scan(reg).reverse.map {|clause| clause.strip.reverse}
  
    matches.each do |match|
      yield match
    end
  end
  </code></pre>