title: Python regex matching pattern not surrounded by double quotes
body: <p>I'm not comfortable with regex, so I need your help with this one, which seems tricky to me.</p>
  
  <p>Let's say I've got the following string : </p>
  
  <pre><code>string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
  </code></pre>
  
  <p>What would be the regex to get <code>title:hello</code>, <code>title:world</code>, remove these strings from the original one and leave <code>"title:quoted"</code> in it, because it's surrounded by double quotes ?</p>
  
  <p>I've already seen <a href="https://stackoverflow.com/questions/11792258/python-regex-to-replace-a-string-if-not-surrounded-by-single-quotes">this similar SO answer</a>, and here is what I ended up with :</p>
  
  <pre><code>import re
  
  string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
  
  def replace(m):
      if m.group(1) is None:
          return m.group()
  
      return m.group().replace(m.group(1), "")
  
  regex = r'\"[^\"]title:[^\s]+\"|([^\"]*)'
  cleaned_string = re.sub(regex, replace, string)
  
  assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3'
  </code></pre>
  
  <p>Of course, it does not work, and I'm not surprised, because regex are esoteric to me.</p>
  
  <p>Thank you for your help !</p>
  
  <h1>Final solution</h1>
  
  <p>Thanks to your answers, here is the final solution, working for my needs :</p>
  
  <pre><code>import re
  matches = []
  
  def replace(m):
      matches.append(m.group())
      return ""
  
  string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3'
  regex = '(?&lt;!")title:[^\s]+(?!")'
  cleaned_string = re.sub(regex, replace, string)
  
  # remove extra withespaces
  cleaned_string = ' '.join(cleaned_string.split())
  
  assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3'
  assert matches[0] == "title:hello"
  assert matches[1] == "title:world"
  </code></pre>