Pregunta

I want to search a string with my regex, but my regex doesn't match anything ...

This is the content I have:

<h4>Text</h4>
    <p><span>Some text I want to catch</p></span>
    <p><span>Some text I want to catch</p></span>
    <p><span>Some text I want to catch</p></span>
<h4>Other Text</h4>
    <p><span>...<p><span>
    ...

This is my NSRegularExpression:

NSString *regex = @"<h4>Text</h4>(.*?)<h4>";

NSError *error = nil;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:&error];

NSRange rangeOfString = NSMakeRange(0, content.length);

NSArray *matches = [[NSArray alloc] init];
matches = [pattern matchesInString:content options:0 range:rangeOfString];

NSString *matchText;
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];

for (NSTextCheckingResult *match in matches) {
    matchText = [content substringWithRange:[match rangeAtIndex:1]];
    [mutableArray addObject:matchText];
}

I want to catch the text (with tags) between the two headlines, but my NSArray "matches" / NSMutableArray "mutableArray" is still empty. My other regex are working ... I checked this regex in an online regex-evaluator and got my text but in my application this regular expression doesn't work.

Is something wrong with my code or regular expression?

¿Fue útil?

Solución

By default, the dot . does not match a line separator. Since the text that you want to capture spans multiple lines, you have to add the NSRegularExpressionDotMatchesLineSeparators option:

NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex
             options:NSRegularExpressionDotMatchesLineSeparators
               error:&error];

Alternatively, add (?s) to the pattern to add the "s" flag.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top