开发者

How do I remove a substring from a string using NSRegularExpression?

I am trying to remove a particular part of a string and so far I decided to use RegEx to match the part of the string I would like to remove, but after that I'm not sure how to then remove that particular range from the original string...

I am trying to change 333-333 Anywhere Lane to 333 Anywhere Lane. Basically I am trying to remove any additional numerical digits after the hyphen.

Here is my code:

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 kno开发者_运维知识库w how to remove that..             

}

Any ideas??

Thank you in advance!


In case anyone stumbles upon this and thinks that the accepted answer's link is vague, here is the code:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜