Suche…


Syntax

  • NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern: PATTERN-Optionen: OPTIONS-Fehler: ERROR];
  • NSArray <NSTextCheckingResult *> * results = [Regex MatchesInString: STRING-Optionen: OPTIONS range: RANGE_IN_STRING];
  • NSInteger numberOfMatches = [Regex NumberOfMatchesInString: STRING-Optionen: OPTIONS-Bereich: RANGE_IN_STRING];

Finden Sie alle Zahlen in einer Zeichenfolge

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

Die Ausgabe wird match: 42 und match: 8672 .

Prüfen Sie, ob eine Zeichenfolge mit einem Muster übereinstimmt

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

Die Ausgabe zeigt an, dass die erste Zeichenfolge eine Telefonnummer ist und die zweite nicht.



Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow