2016-04-29 2 views
4

J'essaie d'enlever une partie de la chaîne entre parenthèses. Par exemple, pour la chaîne "(This should be removed) and only this part should remain", après l'utilisation de NSRegularExpression, il doit être "and only this part should remain".Comment supprimer le texte entre parenthèses en utilisant NSRegularExpression?

J'ai ce code, mais rien ne se passe. J'ai testé mon code regex avec RegExr.com et cela fonctionne correctement. J'apprécierais toute aide.

NSString *phraseLabelWithBrackets = @"(test text) 1 2 3 text test"; 
NSError *error = NULL; 
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"/\\(([^\\)]+)\\)/g" options:NSRegularExpressionCaseInsensitive error:&error]; 
NSString *phraseLabelWithoutBrackets = [regexp stringByReplacingMatchesInString:phraseLabelWithBrackets options:0 range:NSMakeRange(0, [phraseLabelWithBrackets length]) withTemplate:@""]; 
NSLog(phraseLabelWithoutBrackets); 
+1

Cochez cette case. http://stackoverflow.com/questions/3741279/how-do-you-remove-parentheses-words-within-a-string-using-nsregularexpression?rq=1 –

Répondre

5

Retirez les délimiteurs regex et assurez-vous excluez également ( dans la classe de caractères:

NSString *phraseLabelWithBrackets = @"(test text) 1 2 3 text test"; 
NSError *error = NULL; 
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]+\\)" options:NSRegularExpressionCaseInsensitive error:&error]; 
NSString *phraseLabelWithoutBrackets = [regexp stringByReplacingMatchesInString:phraseLabelWithBrackets options:0 range:NSMakeRange(0, [phraseLabelWithBrackets length]) withTemplate:@""]; 
NSLog(phraseLabelWithoutBrackets); 

Voir cette IDEONE demo et a regex demo.

Le motif \([^()]+\) correspondra

  • \( - une parenthèse ouverte
  • [^()]+ - 1 ou plusieurs caractères autres que ( et ) (choisir +-* pour correspondre aussi et supprimer des parenthèses vides ())
  • \) - une parenthèse fermante
+1

Fonctionne parfaitement, merci! – Bastek