2

Simple regex question. I have a string on the following format:

[page]
Some text with multi line.
[page/]

[page]
Another text with multi line.
[page/]

[page]
Third text with multi line.
[page/]

What is the regular expression to extract the text between [page] and [page/]?

I am using this code, but I only got the first match.

NSString *path = [[NSBundle mainBundle] pathForResource:@"File" ofType:@"txt"];
NSString *mainText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

NSError *error = NULL;
NSRange range = NSMakeRange(0, mainText.length);

   NSString *pattern = [NSString stringWithFormat:@"(?<=\\[page])(?s)(.*?)(?=\\[page/])"];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
        NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:mainText options:0 range:range];


        if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
            NSString *substringForFirstMatch = [mainText substringWithRange:rangeOfFirstMatch];
            NSLog(@"sub: %@", substringForFirstMatch);
        }

How can I but the text of every matches in NSArray?

Almudhafar
  • 887
  • 1
  • 12
  • 26
  • Why don't you use `matchesInString:options:range:` which return a `NSArray` of `NSTextCheckingResult` (which has a `NSRange` property)? – Larme Mar 14 '15 at 15:20

1 Answers1

2

You can use matchesInString:options:range:, which returns an array of matches as NSTextCheckingResults:

    NSString *pattern = [NSString stringWithFormat:@"(?<=\\[page\\])(.*?)(?=\\[page\\/\\])"];
    NSUInteger options = NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:&error];

    for (NSTextCheckingResult* result in [regex matchesInString:INPUT_STRING 
                                                    options:0 
                                                      range:NSMakeRange(0, [input_string_length])])
    {
      // further code
    }
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563