在目标c我想替换两个字符串之间的字符串。替换两个字符串之间的字符串iphone sdk
例如 “AB anystring YZ”
我要替换的字符串,是 “AB” 和 “YZ” 之间。
有可能吗?请提前帮助
thx。
在目标c我想替换两个字符串之间的字符串。替换两个字符串之间的字符串iphone sdk
例如 “AB anystring YZ”
我要替换的字符串,是 “AB” 和 “YZ” 之间。
有可能吗?请提前帮助
thx。
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];
否则你将不得不获得REGEXKitLite副本,并使用正则表达式的功能,如:
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];
下面是测试代码来执行你的任务。
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
-(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) {
}
}
请编辑您的问题:(i)为您的代码添加_explanation_(只是代码不是'可能'问题的答案)和(ii)修复您的_code block_(因为并非所有代码都在代码中块)。 – 2016-12-12 07:50:49
感谢Thomas.I第一次尝试之一,但它不干活。我不清楚第二个答案。在我的情况下,“ab”和“yz”之间的字符串不是固定长度的string.help我,如果有可能。 – 2010-10-08 10:44:54
afaik在正则表达式中,“。”意味着“任意数量的字符”。您需要下载regexKitLite并将其包含在您的项目中。 – 2010-10-08 11:18:41
嗨托马斯再次感谢。我试过了。没有编译错误,但可能是一些逻辑错误。我把代码。告诉我,如果你有任何建议。 NSString * str = [[NSString alloc] init]; str = @“ab这是demo yz”; NSString * newstr = [[NSString alloc] init]; newstr = [str stringByReplacingOccurrencesOfRegex:@“ab \\ b。\\ byz”withString:@“good”]; – 2010-10-08 12:45:05