2013-12-18 4 views
5

Il metodo dovrebbe restituire TRUE se NSString è qualcosa come @ "{A5B8A206-E14D-429B-BEB0-2DD0575F3BC0} "e FALSE per un NSString come @" bla bla bla"Come verificare la validità di un GUID (o UUID) utilizzando NSRegularExpression o qualsiasi altro modo efficace in Objective-C

sto usando qualcosa come:

- (BOOL)isValidGUID { 

    NSError *error; 

    NSRange range = [[NSRegularExpression regularExpressionWithPattern:@"(?:(\\()|(\\{))?\\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-Z0-9]{12}\\b(?(1)\\))(?(2)\\})" options:NSRegularExpressionCaseInsensitive error:&error] rangeOfFirstMatchInString:self.GUID options:0 range:NSMakeRange(0, [self.GUID length])]; 

    if (self.GUID && range.location != NSNotFound && [self.GUID length] == 38) { 

     return TRUE; 

    } else { 

     return NO; 
    } 
} 

ma non funziona come mi aspettavo.

Importante: GUID che sto usando è racchiuso da parentesi graffe come questo: {A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}

risposta

3

Questa espressione regolare le partite per me

\A\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}\Z 

In breve:

  • \A e \Z è l'inizio e la fine della stringa
  • \{ e \} fuggiasco bracets graffe
  • [A-F0-9]{8} è esattamente 8 caratteri di entrambi 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F

come NSRegularExpression sarebbe simile a questa

NSError *error = NULL; 
NSRegularExpression *regex = 
    [NSRegularExpression regularExpressionWithPattern:@"\\A\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\}\\Z" 
              options:NSRegularExpressionAnchorsMatchLines 
               error:&error]; 
// use the regex to match the string ... 
+0

Grazie funziona ... – Goppinath

3

è possibile utilizzare il seguente metodo per controllare questo:

- (BOOL)isUUID:(NSString *)inputStr 
{ 
    BOOL isUUID = FALSE; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" options:NSRegularExpressionCaseInsensitive error:nil]; 
    NSInteger matches = [regex numberOfMatchesInString:inputStr options:0 range:NSMakeRange(0, [inputStr length])]; 
    if(matches == 1) 
    { 
     isUUID = TRUE; 
    } 
    return isUUID; 
} 
23

questa funzione farà il lavoro ..

012.
-(BOOL)isValidUUID : (NSString *)UUIDString 
{ 
    return (bool)[[NSUUID alloc] initWithUUIDString:U‌​UIDString]; 
} 

Grazie @ Erzékiel

+3

funziona bene per me! Potrebbe essere minimizzato in questo modo: return (bool) [[NSUUID alloc] initWithUUIDString: UUIDString]; –

+0

Grazie. Questa dovrebbe essere una risposta accettata. Funziona perfettamente su iOS 9. – alexburtnik

+0

Semplice e diretto. Grazie. – Peymankh

Problemi correlati