简体   繁体   中英

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

I want to extract string between [ ] brackets

for Example Original string: @"this is a test [to get this string]."

I want to get extract string between [] 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.

Thanks.

看起来表达式是错误的,你需要转义斜杠(例如: @"\\\\[[^\\\\].]*\\\\]" )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM