在目标c中我想替换两个字符串之间的字符串。
例如 “ab anystring yz”
我想替换“ab”和“yz”之间的字符串。
有可能吗?请帮忙
提前thx。答案 0 :(得分:4)
以下是经过测试的代码来执行您的任务。
NSString *string = @"ab anystring yz";
NSString *result = nil;
// Determine "ab" location
NSRange divRange = [string rangeOfString:@"ab" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
// Determine "ab" location according to "yz" location
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [string length] - endDivRange.location;
endDivRange = [string rangeOfString:@"yz" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
// Tags found: retrieve string between them
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
result = [string substringWithRange:divRange];
string =[string stringByReplacingCharactersInRange:divRange withString:@"Replace string"];
}
}
现在您只需检查您将获得的字符串 ab替换字符串yz
答案 1 :(得分:2)
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];
否则你将不得不获得REGEXKitLite的副本并使用正则表达式函数,如:
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];
答案 2 :(得分:-1)
-(NSString*)StrReplace :(NSString*)mainString preMatch:(NSString*) preMatch postMatch:(NSString*) postMatch replacementString:(NSString*) replacementString
{
@try
{
if (![mainString isEqualToString:@""] || [mainString isKindOfClass:[NSNull class]] || mainString==nil)
{
NSArray *preSubstring = [mainString componentsSeparatedByString:preMatch];
NSString *preStr = [preSubstring objectAtIndex:0];
NSArray *postSubstring = [mainString componentsSeparatedByString:postMatch];
NSString *postStr = [postSubstring objectAtIndex:1];
NSString *resultStr = [NSString stringWithFormat:@"%@%@%@%@%@" ,preStr,preMatch,replacementString,postMatch,postStr];
return resultStr;
}
else
{
return @"";
}
}
@catch (NSException *exception) {
}
}