regexcocoansstring

NSString simple pattern matching


Mac OS 10.6, Cocoa project, 10.4 compatibility required.

(Please note: my knowledge of regex is quite slight)

I need to parse NSStrings, for matching cases where the string contains an embedded tag, where the tag format is:

[xxxx]

Where xxxx are random characters.

e.g. "The quick brown [foxy] fox likes sox".

In the above case, I need to grab the string "foxy". (Or nil if no tag is found.)

Each string will only have one tag, and the tag can appear anywhere within the string, or may not appear at all.

Could someone please help with a way to do that, preferably without having to include another library such as RegexKit. Thank you for any help.


Solution

  • I'd suggest something like the following:

    NSString *subString = nil;
    NSRange range1 = [myString rangeOfString:@"["];
    NSRange range2 = [myString rangeOfString:@"]"];
    if ((range1.length == 1) && (range2.length == 1) && (range2.location > range1.location)) {
      NSRange range3;
      range3.location = range1.location+1;
      range3.length = (range2.location - range1.location)-1;
      subString = [myString substringWithRange:range3];
    }