Search code examples
iosobjective-cnsregularexpression

How to Split String With Regular Expression ios objectivec


Below is the Syntax of Java : Code.split("(?<=\\D)(?=\\d)");

I want to convert this in ios objective c

string Code : LR00001 or BLNS-9-M

I want O/p as:

  • if code is LR00001 then Array gives me two values. On 0th index it gives LR and in 1 index it gives me 00001

  • if code is BLNS-9-M then Array[0] BLNS and Array[1] 9-M

This o/p is working in Java but want in ios objective c.

This regular expression: (?<=\\D)(?=\\d) means it finds position in the string where there is a non-digit (\D) character before that position and a digit (\d) after it. i.e matches a position between a non-digit (\D) and a digit (\d).

Following Code I have tried :

1.

NSArray *arrComponents = [strCode componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"(?<=\\D)(?=\\d)"]];

2.

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\D)(?=\\d)" options:0 error:&error];
NSArray* matches = [regex matchesInString:strCode options:0 range:NSMakeRange(0, [strStyleCode length])];
NSTextCheckingResult *match = [regex firstMatchInString:strCode options:0 range: NSMakeRange(0, [strStyleCode length])];
NSLog(@"group1: %@", [strCode substringWithRange:[match rangeAtIndex:0]]);
NSLog(@"group2: %@", [strCode substringWithRange:[match rangeAtIndex:1]]);

3.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"(?<=\\D)(?=\\d)"];

All of the above do not work.

I want the same output in ios objective c.

[LR,00001] [BLNS,9-M]


Solution

  • You may first replace all the matches with a non-used symbol, say, with \x00 null char, and then split with it:

    NSError *error = nil;
    NSString *str = @"LR00001";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\D)(?=\\d)" options:nil error:&error];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:@"\x00"];
    NSArray *chunks = [modifiedString componentsSeparatedByString: @"\x00"];
    for(NSString *c in chunks) {
        NSLog(@"%@", c);
    }
    

    It prints LR and 00001.

    See the online demo.