title: How to write regular expressions in Objective C (NSRegularExpression)?
body: <p>I have this regex working when I test it in PHP but it doesn't work in Objective C:</p>
  <pre><code>(?:www\.)?((?!-)[a-zA-Z0-9-]{2,63}(?&lt;!-))\.?((?:[a-zA-Z0-9]{2,})?(?:\.[a-zA-Z0-9]{2,})?)
  </code></pre>
  <p>I tried escaping the escape characters but that doesn't help either. Should I escape any other character?</p>
  <p>This is my code in Objective C:</p>
  <pre><code>NSMutableString *searchedString = [NSMutableString stringWithString:@&quot;domain-name.tld.tld2&quot;];
  NSError* error = nil;
  
  NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@&quot;(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?&lt;!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)&quot; options:0 error:&amp;error];
  NSArray* matches = [regex matchesInString:searchedString options:0 range:NSMakeRange(0, [searchedString length])];
  for ( NSTextCheckingResult* match in matches )
  {
      NSString* matchText = [searchedString substringWithRange:[match range]];
      NSLog(@&quot;match: %@&quot;, matchText);
  }
  </code></pre>
  <p>-- UPDATE --</p>
  <p>This regex returns (in PHP) the array with values &quot;domain-name&quot; and &quot;tld.tld2&quot; but in Objective C i get only one value: &quot;domain-name.tld.tld2&quot;</p>
  <p>-- UPDATE 2 --</p>
  <p>This regex extracts 'domain name' and 'TLD' from the string:</p>
  <ul>
  <li>example.com = (example, com)</li>
  <li>example.co.uk = (example, co.uk)</li>
  <li>-test-example.co.u = (test-example, co)</li>
  <li>-test-example.co.uk- = (test-example, co.uk)</li>
  <li>-test-example.co.u-k = (test-example, co)</li>
  <li>-test-example.co-m = (test-example)</li>
  <li>-test-example-.co.uk = (test-example)</li>
  </ul>
  <p>it takes the valid domain name (not starting or ending with '-' and between 2 and 63 characters long), and up to two parts of a TLD if the parts are valid (at least two characters long containing only letters and numbers)</p>