title: Target double quotes using regular expressions in Swift
body: <p>I have been trying to extract a piece of text inside an string using regular expressions in Swift. The text I want to extract is inside double quotes so I'm trying to target those double quotes and get the piece of text inside.</p>
  
  <p>This is the RegExp that I'm using: <code>(?&lt;=")(?:\\.|[^"\\])*(?=")</code></p>
  
  <p>It work pretty well with any kind of text and it could be even simpler since I'm looking for anything that could be inside those double quotes.</p>
  
  <p>When I try to use this RegExp with Swift I have to scape the double quotes in it, but for some reason the RegExp doesn't work with escaped double quotes e.g. <code>(?&lt;=\")(?:\\.|[^\"\\])*(?=\")</code>.</p>
  
  <p>Even if I try some as simple as this <code>\"</code> the RegExp doesn't match any double quote in the string.</p>
  
  <p><strong>Code Example</strong></p>
  
  <pre><code>func extractText(sentence: String?) -&gt; String {
      let pattern = "(?&lt;=\")(?:\\.|[^\"\\])*(?=\")"
      let source = sentence!
  
      if let range = source.range(of: pattern, options: .regularExpression) {
          return "Text: \(source[range])"
      }
  
      return ""
  }
  
  extractText("Hello \"this is\" a test") -&gt; "this is"
  </code></pre>
  
  <p><strong>To have in mind:</strong></p>
  
  <ul>
  <li>All these RegExps must be inside double quotes to create the string literal that is going to be used as a pattern.</li>
  <li>I'm using the String's <code>range</code> method with the <code>.regularExpression</code> option to match the content.</li>
  <li>I'm using Swift 4 with an Xcode 9 Playground</li>
  </ul>
  
  <p><em>How can I scape double quotes in Swift to successfully match these in a string?</em></p>
  
  <h2>Solution</h2>
  
  <p>Thanks to @Atlas_Gondal and @vadian I noticed the problem "in part" is not the RegExp but the string I'm getting which is using a different type of double quotes <code>“ ... ”</code> so I have to change my pattern to something like this <code>"(?&lt;=“).*(?=”)"</code> in order to use it.</p>
  
  <p>The resulted code looks like this:</p>
  
  <pre><code>func extractText(sentence: String?) -&gt; String {
      let pattern = "(?&lt;=“).*(?=”)"
      let source = sentence!
  
      if let range = source.range(of: pattern, options: .regularExpression) {
          return "\(source[range])"
      }
  
      return ""
  }
  </code></pre>