2011-10-05 23 views
7

Come estrarre il valore "6" tra i tag "badgeCount" utilizzando NSRegularExpression. Di seguito è riportata la risposta dal server:NSRegularExpression per estrarre il testo tra due tag XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><badgeCount>6</badgeCount><rank>2</rank><screenName>myName</screenName> 

seguito è il codice che ho provato ma non ottenere il successo. In realtà si va in parte il resto e stampe "Valore della regex è pari a zero":

NSString *responseString = [[NSString alloc] initWithBytes:[responseDataForCrntUser bytes] length:responseDataForCrntUser.length encoding:NSUTF8StringEncoding]; 

NSError *error; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=badgeCount>)(?:[^])*?(?=</badgeCount)" options:0 error:&error]; 
if (regex != nil) { 
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:responseString options:0 range:NSMakeRange(0, [responseString length])]; 
    NSLog(@"NOT NIL"); 
    if (firstMatch) { 
     NSRange accessTokenRange = [firstMatch rangeAtIndex:1]; 
     NSString *value = [urlString substringWithRange:accessTokenRange]; 
     NSLog(@"Value: %@", value); 
    } 
} 
else 
    NSLog(@"Value of regex is nil"); 

Se si potesse fornire il codice di esempio che sarebbe molto apprezzato.

NOTA: non desidero utilizzare NSXMLParser.

+0

Perché non ti vuoi se un parser xml analizza xml? – Mat

+0

E che cosa hai provato finora? – Mat

+0

Nessuna necessità di NSXMLParser per estrarre solo un paio di valori ... Ho ottenuto l'espressione regolare necessaria "(? <=badgeCount>) (?: [^]) *? (? = Prazi

risposta

18

Esempio:

NSString *xml = @"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><badgeCount>6</badgeCount><rank>2</rank><screenName>myName</screenName>"; 
NSString *pattern = @"<badgeCount>(\\d+)</badgeCount>"; 

NSRegularExpression *regex = [NSRegularExpression 
             regularExpressionWithPattern:pattern 
             options:NSRegularExpressionCaseInsensitive 
             error:nil]; 
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:xml options:0 range:NSMakeRange(0, xml.length)]; 

NSRange matchRange = [textCheckingResult rangeAtIndex:1]; 
NSString *match = [xml substringWithRange:matchRange]; 
NSLog(@"Found string '%@'", match); 

NSLog uscita:

Found string '6' 
+0

Se voglio ottenere il valore "myName" tra il tag ho bisogno di creare una nuova espressione regolare o potrei farlo nello stesso. – Prazi

+1

Richiederebbe una nuova espressione regolare perché "\ d +" specifica una o più cifre. Per un nome avrete bisogno di qualcosa come "\ S +" (se non ci sono spazi nel nome). C'è una regex più generale che dovrebbe funzionare in entrambi i casi: @ " ([^ <] +)", che dice tutto fino al carattere "<". – zaph

+0

Grazie per tutto il tuo aiuto. Molto apprezzato. .... Ciò significa che ho bisogno di due modelli separati 1. ([^ <] +) per ottenere badgeCount 2. ([^ <] +) per ottenere screenName. – Prazi

1

farlo in rapida 3,0

func getMatchingValueFrom(strXML:String, tag:String) -> String { 
    let pattern : String = "<"+tag+">(\\d+)</"+tag+">" 
    let regexOptions = NSRegularExpression.Options.caseInsensitive 

    do { 
     let regex = try NSRegularExpression(pattern: pattern, options: regexOptions) 
     let textCheckingResult : NSTextCheckingResult = regex.firstMatch(in: strXML, options: NSRegularExpression.MatchingOptions(rawValue: UInt(0)), range: NSMakeRange(0, strXML.characters.count))! 
     let matchRange : NSRange = textCheckingResult.rangeAt(1) 
     let match : String = (strXML as NSString).substring(with: matchRange) 
     return match 
    } catch { 
     print(pattern + "<-- not found in string -->" + strXML) 
     return "" 
    } 
} 

PS: Questo è corrispondente rapida soluzione di soluzione @ di zaph in obj- c