我想知道某个字符串是否有正则表达式。
我编写了下面的代码,以便匹配类似于以下内容的字符串:
" A | 3 | A3 \ n"
但是下面的代码会得到一系列匹配项。我不想那样,因为我想简单地理解我的响应字符串是否与正则表达式给出的条件匹配。有关如何这样做的任何建议吗?
NSString * response = "A|3|a3\n";
NSRange searchedRange = NSMakeRange(0, [ response length]);
NSString *pattern = @"[ABC]\|[0-9]\|[a][0-9]$";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:response options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches){
NSString* matchText = [response substringWithRange:[match range]];
NSLog(@"match: %@", matchText);
}
答案 0 :(得分:1)
Xcode应该发出警告:
Warning: Unknown escape sequence '\|'
这一行:
NSString *pattern = @"[ABC]\|[0-9]\|[a][0-9]$";
" \"确实逃脱了下一个角色(对于一些特殊的意义,如古典" \ n"),但" \ |"是正常字符串的未知转义序列。所以你必须加倍#34;:
NSString *pattern = @"[ABC]\\|[0-9]\\|[a][0-9]$"
答案 1 :(得分:0)
我认为您正在寻找一种IsMatch()
功能。这是一个例子:
NSRange matchRange = [regex rangeOfFirstMatchInString:response options:NSMatchingReportProgress range:searchedRange];
BOOL isFound = NO;
// Did we find a matching range
if (matchRange.location != NSNotFound)
isFound = YES;