0

我知道有几种不同的方法可以在文件中查找文本,尽管我还没有找到在我正在搜索的字符串之后返回文本的方法。例如,如果我要在 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");    
}
4

2 回答 2

1

您可能想要使用RegexKitLite并执行正则表达式查找:

NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];

虽然没有测试。

于 2012-07-16T06:31:12.063 回答
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);  
}
于 2012-07-16T06:47:46.333 回答