Regular expression in object C

I want to extract only the names from the next line

bob!33@localhost @clement!17@localhost jack!03@localhost

and create an array [@"bob", @"clement", @"jack"].

I tried NSString componentsseparatedbystring:but it did not work properly. Therefore, I plan to upgrade to regEx.

  • How can I extract strings between ranges and add them to an array using regEx in a C object?
  • The source string can contain more than 500 names, will it be a performance issue if I manipulate the string with regEx?
+4
source share
4 answers

You can do this without a regular expression, as shown below (the “Satisfaction!” Sign has a single pattern in all words),

NSString *names = @"bob!33@localhost @clement!17@localhost jack!03@localhost";
NSArray *namesarray = [names componentsSeparatedByString:@" "];
NSMutableArray *desiredArray = [[NSMutableArray alloc] initWithCapacity:0];
[namesarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSRange rangeofsign = [(NSString*)obj rangeOfString:@"!"];
    NSString *extractedName = [(NSString*)obj substringToIndex:rangeofsign.location];
    [desiredArray addObject:extractedName];
}];
NSLog(@"%@",desiredArray);

the output above NSLog will be

(
    bob,
    "@clement",
    jack
)

@ , ,

,

+5
NSMutableArray* nameArray = [[NSMutableArray alloc] init];
NSArray* youarArray = [yourString componentsSeparatedByString:@" "];
for(NSString * nString in youarArray) {
   NSArray* splitObj = [nString componentsSeparatedByString:@"!"];
   [nameArray addObject:[splitObj[0]]];
}    
NSLog(@"%@", nameArray);
+5

- , :

NSString *strNames = @"bob!33@localhost @clement!17@localhost jack!03@localhost";

strNames = [[strNames componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]]
                                  componentsJoinedByString:@""];

NSArray *arrNames = [strNames componentsSeparatedByString:@"localhost"];
NSLog(@"%@", arrNames);

:

(
    bob,
    clement,
    jack,
    ""
)

. -

:

  • " localhost"

, ,

+4

, , , , , , , - :

NSString *_names = @"bob!33@localhost @clement!17@localhost jack!03@localhost";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:@" ?@?(.*?)!\\d{2}@localhost" options:NSRegularExpressionCaseInsensitive error:&_error];
NSMutableArray *_namesOnly = [NSMutableArray array];
if (!_error) {
    NSLock *_lock = [[NSLock alloc] init];
    [_regExp enumerateMatchesInString:_names options:NSMatchingReportProgress range:NSMakeRange(0, _names.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        if (result.numberOfRanges > 1) {
            if ([_lock tryLock]) [_namesOnly addObject:[_names substringWithRange:[result rangeAtIndex:1]]], [_lock unlock];
        }
    }];
} else {
    NSLog(@"error : %@", _error);
}

...

NSLog(@"_namesOnly : %@", _namesOnly);

... :

_namesOnly : (
    bob,
    clement,
    jack
)
+4

All Articles