开发者

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

开发者 https://www.devze.com 2023-02-04 13:38 出处:网络
I want to extract string between [ ] brackets for Example Original string: @\"this is a test [to get this string].\"

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 [] i.e "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 (++开发者_JAVA百科count >= 100) *stop = YES;

 }]; 

Please let me know if I am doing something wrong.

Thanks.


Looks like the expression is wrong, you need to escape the slashes (eg : @"\\[[^\\].]*\\]").

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号