【问题标题】:Extract text between two markers with Regular Expression使用正则表达式提取两个标记之间的文本
【发布时间】:2015-05-17 00:19:38
【问题描述】:

简单的正则表达式问题。我有以下格式的字符串:

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

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

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

提取[page][page/]之间的文本的正则表达式是什么?

我正在使用这段代码,但我只得到了第一个匹配项。

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);
        }

我怎样才能在 NSArray 中找到每个匹配项的文本?

【问题讨论】:

  • 你为什么不使用matchesInString:options:range:,它返回一个NSArrayNSTextCheckingResult(它有一个NSRange 属性)?

标签: ios regex nsregularexpression


【解决方案1】:

您可以使用matchesInString:options:range:,它将匹配数组作为 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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多