2011-10-05 4 views
7

Comment extraire la valeur "6" entre les balises "badgeCount" en utilisant NSRegularExpression. Voici la réponse du serveur:NSRegularExpression pour extraire du texte entre deux balises XML

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

Voici le code que j'ai essayé mais qui n'a pas réussi. En fait, il va dans une partie autre et imprime « la valeur de regex est nul »:

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

Si vous pouvez fournir des exemples de code qui serait très apprécié.

REMARQUE: je ne souhaite pas utiliser NSXMLParser.

+0

Pourquoi ne veux-tu pas un analyseur xml pour analyser XML? – Mat

+0

Et qu'avez-vous essayé jusqu'à présent? – Mat

+0

Pas besoin de NSXMLParser pour extraire juste quelques valeurs ... J'ai eu l'expression régulière nécessaire "(? <=badgeCount>) (?: [^]) *? (? = Prazi

Répondre

18

Exemple:

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

sortie NSLog:

Found string '6' 
+0

Si je veux obtenir la valeur "myName" entre l'étiquette dois-je créer une nouvelle expression régulière ou pourrais-je le faire dans le même. – Prazi

+1

Il faudrait une nouvelle regex car "\ d +" spécifie un ou plusieurs chiffres. Pour un nom, vous aurez besoin de quelque chose comme "\ S +" (s'il n'y a pas d'espaces dans le nom). Il y a une regex plus générale qui devrait fonctionner dans les deux cas: @ " ([^ <] +)", qui dit n'importe quoi jusqu'au caractère "<". – zaph

+0

Merci pour votre aide. Très appréciée. .... Donc cela signifie que j'ai besoin de deux modèles distincts 1. ([^ <] +) pour obtenir badgeCount 2. ([^ <] +) pour obtenir screenName. – Prazi

1

Pour le faire dans swift 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: Ceci est correspondant solution rapide de la solution de @ Zaph dans obj- c

Questions connexes