从特定字符串集中提取String

时间:2015-09-23 09:46:50

标签: ios objective-c nsstring

我有一个文字: sometext [string1 string2] someText

我想从此文本中检索string1和string2作为单独的字符串 我怎样才能在目标中解析它?c?

4 个答案:

答案 0 :(得分:0)

我找到了解决方案

  NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:@"["];
    NSString *parsedOne = [arrayOne objectAtIndex:1];

    NSArray *arrayTwo = [parsedOne componentsSeparatedByString:@"]"];
    NSString *parsedTwo = [arrayTwo objectAtIndex:0];

    NSArray *arrayThree = [parsedTwo componentsSeparatedByString:@" "];
    NSString *className = [arrayThree objectAtIndex:0];
    NSString *functionName = [arrayThree objectAtIndex:1];

非常感谢

答案 1 :(得分:0)

也许这样的事情对你有用

NSString * string = @"sometext[string1 string2]sometext";
NSString * pattern = @"(.*)\[(.+) (.+)\](.*)"

NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];

if (match) {

    NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
    NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];

    // do something with substring1 and substring2
}

答案 2 :(得分:0)

您可以使用此简单方法方法

NSString *str = @"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:@"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:@"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:@" "]; 

结果数组将包含您所需的Reuslt

答案 3 :(得分:0)

为了完整性 - 如果您尝试从具有已知模式的字符串中提取字符串,则可以使用cell.selected = true

这一次通过字符串。

NSScanner

将输出放入控制台:

NSString *string = @"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];

NSString *str1;
NSString *str2;

[scanner scanUpToString:@"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:@"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:@"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'

// Log the output.
NSLog(@"First String: %@", str1);
NSLog(@"Second String: %@", str2);