views:

46

answers:

1

in objective c i want to replace string which is between two string.

For example "ab anystring yz"

i want to replace string which is between "ab" and "yz".

is it possible to do? Please Help

thx in advance.

+1  A: 
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];

otherwise you're going to have to get a copy of REGEXKitLite and use a regex function like:

NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];
Thomas Clayson
Thanks Thomas.I tried first one but it doesn't work.I am not clear about second answer.In my case string between "ab" and "yz" is not fixed length string.help me if is it possible.
Viral Narshana
afaik a fullstop `.` in regex means "any amount of characters". You need to download regexKitLite and include it in your project.
Thomas Clayson
Hi Thomas Thanks again. I tried it.No compilation error but might be some logic error.I put the code.Tell me if u have any suggestion for it. NSString *str = [[NSString alloc] init];str = @"ab This is demo yz";NSString *newstr = [[NSString alloc] init];newstr = [str stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"good"];
Viral Narshana
I got the answer. NSString *str = [[NSString alloc] init];str = @"ab this is demo yz";NSString *newstr = [[NSString alloc] init];newstr = [str stringByReplacingOccurrencesOfRegex:@" (.*) " withString:@"good"];
Viral Narshana
May I suggest that instead of doing `NSString *str = [[NSString alloc] init]; str= @"Hello";` You can just do: `NSString *str = [NSString stringWithFormat:@"Hello"];` then you don't have to worry about memory management or anything. :) and its just a little nicer to code and read. :)
Thomas Clayson