简单的正则表达式问题。我有以下格式的字符串:
[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:
,将匹配项数组作为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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句