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 NSTextCheckingResult
has multiple items obtained by indexing into it.
[match rangeAtIndex:0];
is the full match.
[match rangeAtIndex:1];
(if it exists) is the first capture group match.
etc.
You can use something like this:
NSString *searchedString = @"domain-name.tld.tld2";
NSRange searchedRange = NSMakeRange(0, [searchedString length]);
NSString *pattern = @"(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?
NSLog output:
match: domain-name.tld.tld2
domain-name
tld.tld2
Do test that the match ranges are valid.
More simply in this case:
NSString *searchedString = @"domain-name.tld.tld2";
NSRange searchedRange = NSMakeRange(0, [searchedString length]);
NSString *pattern = @"(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?
Swift 3.0:
let searchedString = "domain-name.tld.tld2"
let nsSearchedString = searchedString as NSString
let searchedRange = NSMakeRange(0, searchedString.characters.count)
let pattern = "(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?
print output:
match: domain-name.tld.tld2
matchText1: domain-name
matchText2: tld.tld2
More simply in this case:
do {
let regex = try NSRegularExpression(pattern:pattern, options: [])
let match = regex.firstMatch(in:searchedString, options:[], range:searchedRange)
let matchText1 = nsSearchedString.substring(with: match!.rangeAt(1))
print("matchText1: \(matchText1)")
let matchText2 = nsSearchedString.substring(with: match!.rangeAt(2))
print("matchText2: \(matchText2)")
} catch let error as NSError {
print(error.localizedDescription)
}
print output:
matchText1: domain-name
matchText2: tld.tld2