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 に答える