如何解析NSString

时间:2016-04-25 05:31:50

标签: ios objective-c nsstring

字符串为myAgent(9953593875).Amt:Rs.594,并希望从中提取9953593875。这是我试过的:

NSRange range  =  [feDetails rangeOfString:@"."];
NSString *truncatedFeDetails = [feDetails substringWithRange:NSMakeRange(0, range.location)];
NSLog(@"truncatedString-->%@",truncatedFeDetails);

输出:truncatedString-->AmzAgent(9953593875)

3 个答案:

答案 0 :(得分:4)

或者你喜欢这样:

NSString *string = @"myAgent(9953593875).Amt:Rs.594.";

NSRange rangeOne = [string rangeOfString:@"("];
NSRange rangeTwo = [string rangeOfString:@")"];

if (rangeOne.location != NSNotFound && rangeTwo.location != NSNotFound) {
    NSString *truncatedFeDetails = [string substringWithRange:NSMakeRange(rangeOne.location + 1, rangeTwo.location - rangeOne.location - 1)];
    NSLog(@"%@",truncatedFeDetails);

}

答案 1 :(得分:2)

喜欢

<强>步骤1

//首先根据--- OnDataShortPhraseResponseReceivedHandler --- ********* Final n-BEST Results ********* Confidence=High, Text="What's the weather like?" Confidence=High, Text="What's the weather like?"

拆分字符串

例如

.

在这里你得到NSString *value = @"myAgent(9953593875).Amt:Rs.594.How I get 9953593875 only"; NSArray *arr = [value componentsSeparatedByString:@"."]; NSString * AmzAgent = [arr firstObject]; // or use [arr firstObject]; NSLog(@"with name ==%@",AmzAgent);

的输出

<强>步骤-2

在这里使用替换字符串,如

myAgent(9953593875)

最后输出为AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:@"myAgent(" withString:@""]; AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:@")" withString:@""]; NSLog(@"final ==%@",AmzAgent);

enter image description here

答案 2 :(得分:0)

试试这个

NSString *str = @"myAgent(9953593875).Amt:Rs.594.";
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"(?<=\\()\\d+(?=\\))"
                              options:NSRegularExpressionCaseInsensitive
                              error:nil];
NSString *result = [str substringWithRange:[regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])].range];
//result = 9953593875