2016-04-25 98 views
0

該字符串是myAgent(9953593875).Amt:Rs.594並且想要從中提取9953593875。這裏是我的嘗試:如何解析NSString

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

此輸出:truncatedString-->AmzAgent(9953593875)

回答

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); 

} 
+0

謝謝老兄。它的工作。 – akshay

2

不喜歡

第1步

//拆分第一款基於.

的字符串示例

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); 

在這裏u得到的myAgent(9953593875)

步驟2

在這裏

使用替代像

AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:@"myAgent(" 
               withString:@""]; 
AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:@")" 
               withString:@""]; 

NSLog(@"final ==%@",AmzAgent); 

串最後你會得到作爲輸出9953593875

enter image description here

+0

@ 「myAgent」 是dynamic.It可以改變。 – akshay

+0

@akshay - 哦好吧好吧然後採取lovo答案,它會幫助你,我不想重寫代碼兄 –

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