Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write regular expressions in Objective C (NSRegularExpression)?
    text
    copied!<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:@"domain-name.tld.tld2"]; NSError* error = nil; NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?&lt;!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)" 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(@"match: %@", matchText); } </code></pre> <p>-- UPDATE --</p> <p>This regex returns (in PHP) the array with values "domain-name" and "tld.tld2" but in Objective C i get only one value: "domain-name.tld.tld2"</p> <p>-- UPDATE 2 --</p> <p>This regex extracts 'domain name' and 'TLD' from the string:</p> <ul> <li>domain.com = (domain, com)</li> <li>domain.co.uk = (domain, co.uk)</li> <li>-test-domain.co.u = (test-domain, co)</li> <li>-test-domain.co.uk- = (test-domain, co.uk)</li> <li>-test-domain.co.u-k = (test-domain, co)</li> <li>-test-domain.co-m = (test-domain)</li> <li>-test-domain-.co.uk = (test-domain)</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> <p>Hope this explanation helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload