如何使用NSRegularExpression从字符串中删除子字符串?

时间:2011-04-09 17:19:42

标签: objective-c cocoa-touch ios4

我正在尝试删除字符串的特定部分,到目前为止,我决定使用RegEx来匹配我想删除的字符串部分,但之后我不知道如何删除该特定范围来自原始字符串...

我正在尝试将333-333 Anywhere Lane更改为333 Anywhere Lane。基本上我想删除连字符后的任何附加数字。

这是我的代码:

address = @"333-333 Anywhere Lane";

NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-[0-9]*" options:NSRegularExpressionCaseInsensitive error:&error];

NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:address options:0 range:NSMakeRange(0, [address length])];

NSLog(@"range of match = %d", rangeOfFirstMatch);

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {

    address = [address substringWithRange:rangeOfFirstMatch];
    NSLog(@"substring = %@", address8);
    //i cant get the -333 but i don't know how to remove that..             

}

任何想法??

提前谢谢!

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

如果有人偶然发现并且认为接受的答案的链接含糊不清,请输入以下代码:

address = @"333-333 Anywhere Lane";

NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"-[0-9]*" options:NSRegularExpressionCaseInsensitive error:&error];

address = [regex stringByReplacingMatchesInString:address options:0 range:NSMakeRange(0, [address length]) withTemplate:@""];

NSLog(@"substring = %@", address8);