I have this regex working when I test it in PHP but it doesn't work in Objective C:
(?:www.)?((?!-)[a-zA-Z0-9-]{2,63}(?<!-)).?((?:[a-zA-Z0-9]{2,})?(?:.[a-zA-Z0-9]{2,})?)
I tried escaping the escape characters but that doesn't help either. Should I escape any other character?
This is my code in Objective C:
NSMutableString *searchedString = [NSMutableString stringWithString:@"domain-name.tld.tld2"];
NSError* error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(?:www\.)?((?!-)[a-zA-Z0-9-]{2,63}(?<!-))\.?((?:[a-zA-Z0-9]{2,})?(?:\.[a-zA-Z0-9]{2,})?)" options:0 error:&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);
}
-- UPDATE --
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"
-- UPDATE 2 --
This regex extracts 'domain name' and 'TLD' from the string:
- domain.com = (domain, com)
- domain.co.uk = (domain, co.uk)
- -test-domain.co.u = (test-domain, co)
- -test-domain.co.uk- = (test-domain, co.uk)
- -test-domain.co.u-k = (test-domain, co)
- -test-domain.co-m = (test-domain)
- -test-domain-.co.uk = (test-domain)
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)
Hope this explanation helps.
See Question&Answers more detail:os