Ricerca…


Sintassi

  • NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern: Opzioni PATTERN: OPTIONS errore: ERRORE];
  • NSArray <NSTextCheckingResult *> * results = [regex matchesInString: STRING options: OPTIONS range: RANGE_IN_STRING];
  • NSInteger numberOfMatches = [regex numberOfMatchesInString: Opzioni STRING: intervallo OPTIONS: RANGE_IN_STRING];

Trova tutti i numeri in una stringa

NSString *testString = @"There are 42 sheep and 8672 cows.";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSArray *matches = [regex matchesInString:testString
                                  options:0
                                    range:NSMakeRange(0, testString.length)];

for (NSTextCheckingResult *matchResult in matches) {
    NSString* match = [testString substringWithRange:matchResult.range];
    NSLog(@"match: %@", match);
}

Il risultato sarà match: 42 e match: 8672 .

Controlla se una stringa corrisponde a un modello

NSString *testString1 = @"(555) 123-5678";
NSString *testString2 = @"not a phone number";

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\(\\d{3}\\) \\d{3}\\-\\d{4}$"
                                                                       options:NSRegularExpressionCaseInsensitive error:&error];

NSInteger result1 = [regex numberOfMatchesInString:testString1 options:0 range:NSMakeRange(0, testString1.length)];
NSInteger result2 = [regex numberOfMatchesInString:testString2 options:0 range:NSMakeRange(0, testString2.length)];

NSLog(@"Is string 1 a phone number? %@", result1 > 0 ? @"YES" : @"NO");
NSLog(@"Is string 2 a phone number? %@", result2 > 0 ? @"YES" : @"NO");

L'output mostrerà che la prima stringa è un numero di telefono e la seconda non lo è.



Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow