objective c - Unexpected behavior by [NSRegularExpression stringByReplacingMatchesInString] -
i tinkering objective-c today, i'm running odd behavior. trying replace non-alphabetic lowercase characters nsstring. had boiled down to:
int main(int argc, const char * argv[]) { @autoreleasepool { nserror *error; nsregularexpression *pattern = [[nsregularexpression alloc] initwithpattern:@"/[^abcdefghijklmnopqrstuvwxyz]/" options:0 error:&error]; nsstring *replacablestuff = @"a b c\nd e"; nslog(@"%@", [pattern stringbyreplacingmatchesinstring:replacablestuff options:0 range:nsmakerange(0, [replacablestuff length]) withtemplate:@""]); } return 0; }
however, replacement never seems happen; running logs "a b c\nd e" log thingie. (i expecting see "abcde".) tried simpler patterns /[aeiou]/
or /a/
, no matter try, stringbyreplacingmatchesinstring method doesn't seem replacing anything. overlooking?
you need remove slashes on both sides of pattern. slashes not metacharacters in cocoa's regular expressions, strings matched current expression single letters slashes on both sides - /a/
, /b/
, /c/
, , on.
you can use range in character class, this:
nsregularexpression *pattern = [[nsregularexpression alloc] initwithpattern:@"[^a-z]" options:0 error:&error];
Comments
Post a Comment