Failed to extract string using NSRegularExpression (regex pattern) - iphone

I want to extract a line between [] brackets

for example, Original line: @ "this is a test [to get this line]".

I want to get the extract string from [] ie "to get this string" in this example.

Please find below my code

NSMutableString *predicateString = [[NSMutableString alloc] initWithFormat:@"%@",@"this is a test [to get this string]."];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[[^\].]*\]"
                     options:NSRegularExpressionCaseInsensitive
                    error:&error];


 NSMutableArray *rangeArray = [[NSMutableArray alloc] init];
 __block NSUInteger count = 0;
 [regex enumerateMatchesInString:predicateString options:0 range:NSMakeRange(0, [predicateString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
  NSRange matchRange = [match range];
  matchRange.length = matchRange.length+1;
  NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  NSLog(@"matchRange.location: %d",matchRange.location);
  NSLog(@"matchRange.length: %d",matchRange.length);

  if (++count >= 100) *stop = YES;

 }]; 

Please let me know if I am doing something wrong.

Thank.

+3
source share
1 answer

It looks like the expression is wrong, you need to avoid the slash (for example:) @"\\[[^\\].]*\\]".

+1
source

Source: https://habr.com/ru/post/1784952/


All Articles