我知道有几种不同的方法可以在文件中查找文本,虽然我找不到在我搜索的字符串后返回文本的方法。例如,如果我要搜索file.txt中的术语foo
并想要返回bar
,那么在不知道bar
或长度的情况下我该怎么做?
这是我正在使用的代码:
if (!fileContentsString) {
NSLog(@"Error reading file");
}
// Create the string to search for
NSString *search = @"foo";
// Search the file contents for the given string, put the results into an NSRange structure
NSRange result = [fileContentsString rangeOfString:search];
// -rangeOfString returns the location of the string NSRange.location or NSNotFound.
if (result.location == NSNotFound) {
// foo not found. Bail.
NSLog(@"foo not found in file");
return;
}
// Continue processing
NSLog(@"foo found in file");
}
答案 0 :(得分:1)
您可能希望使用RegexKitLite并执行正则表达式查找:
NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];
虽然没有测试。
答案 1 :(得分:1)
您可以使用[NSString substringFromIndex:]
if (result.location == NSNotFound)
{
// foo not found. Bail.
NSLog(@"foo not found in file");
return;
}
else
{
int startingPosition = result.location + result.length;
NSString* foo = [fileContentsString substringFromIndex:startingPosition]
NSLog(@"found foo = %@",foo);
}