52

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:

  • example.com = (example, com)
  • example.co.uk = (example, co.uk)
  • -test-example.co.u = (test-example, co)
  • -test-example.co.uk- = (test-example, co.uk)
  • -test-example.co.u-k = (test-example, co)
  • -test-example.co-m = (test-example)
  • -test-example-.co.uk = (test-example)

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)

2

2 Answers 2

84

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}(?<!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)";
NSError  *error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:searchedString options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches) {
    NSString* matchText = [searchedString substringWithRange:[match range]];
    NSLog(@"match: %@", matchText);
    NSRange group1 = [match rangeAtIndex:1];
    NSRange group2 = [match rangeAtIndex:2];
    NSLog(@"group1: %@", [searchedString substringWithRange:group1]);
    NSLog(@"group2: %@", [searchedString substringWithRange:group2]);
}

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}(?<!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)";
NSError  *error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:searchedString options:0 range: searchedRange];
NSLog(@"group1: %@", [searchedString substringWithRange:[match rangeAtIndex:1]]);
NSLog(@"group2: %@", [searchedString substringWithRange:[match rangeAtIndex:2]]);

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}(?<!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)"

do {
    let regex = try NSRegularExpression(pattern:pattern, options: [])
    let matches = regex.matches(in:searchedString, options:[], range:searchedRange)
    for match in matches {
        let matchText = nsSearchedString.substring(with:match.range);
        print("match: \(matchText)");

        let group1 : NSRange = match.rangeAt(1)
        let matchText1 = nsSearchedString.substring(with: group1)
        print("matchText1: \(matchText1)")

        let group2 = match.rangeAt(2)
        let matchText2 = nsSearchedString.substring(with: group2)
        print("matchText2: \(matchText2)")
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

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

5
  • my code above currently displays all of the matched results (full match, domain-name, TLDs) and that works when I test that regex online but it returns only the first value (full match) when tested in Objective C.
    – budiDino
    Feb 14, 2012 at 12:35
  • Looks like I have a problem with the "NSMutableString stringWithString" part because the regex doesn't match the same things online VS Objective C
    – budiDino
    Feb 14, 2012 at 12:36
  • 2
    I'm sorry, you were right. Looks like I didn't understand how to obtain the results correctly. I'm a web developer at my core and Objective C just makes everything I try to do at least 2 times harder than it is in PHP :) Thanks again.
    – budiDino
    Feb 14, 2012 at 12:51
  • 2
    The whole NSTextCheckingResult is a world of hurt because it does to much and is over-kill for regex. It is not readily apparent that it contains the capture groups.
    – zaph
    Feb 14, 2012 at 12:55
  • lol, I just saw my 2nd comment here. I was thinking about "NSRegularExpression regularExpressionWithPattern" but copy-pasted "NSMutableString stringWithString" :) Anyway, I love the community here!
    – budiDino
    Feb 15, 2012 at 9:18
17

According to Apple's documentation, these characters must be quoted (using \) to be treated as literals:

* ? + [ ( ) { } ^ $ | \ . /

It would also help if you could explain what you are trying to achieve. Do you have any test fixtures?

4
  • In the standard regex sense? or to be treated as regex operators?
    – Adam Waite
    Feb 14, 2013 at 14:37
  • I have been trying regex in obj-c, but I can't get \[ to work. Any ideas? Sep 17, 2013 at 3:27
  • 11
    You must escape the backslash first. \\[ Dec 4, 2013 at 17:00
  • I would also add that if you are looking to search for the # (as a literal), the NSRegularExpression init will fail. I replaced this with \u0023 (or rather \\u0023) and that worked.
    – horseshoe7
    Aug 17, 2017 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.