如何检查NSString中是否存在以下格式:两个空格后跟一个数字后跟一个句点。例如:
" 1."
" 2."
" 5."
...
" 100."
这需要正则表达式吗?我从[myString rangeOfString:@" [0-9]+\."].location]
开始,但我不知道如何检查任何给定的数字0-9
答案 0 :(得分:1)
示例代码:
NSString *s = @"qw 5.vds";
NSRange range = [s rangeOfString:@" [0-9]\\." options:NSRegularExpressionSearch];
BOOL found = range.location != NSNotFound;
NSLog(@"found: %@", found?@"Yes":@"No");
NSUInteger dotLocation = NSNotFound;
if (found) {
dotLocation = NSMaxRange(range)-1;
}
NSLog(@"dot location: %lu", dotLocation);
NSLog输出:
发现:是的 点位置:5
答案 1 :(得分:0)
正则表达式确实是最简单的方法。表达式如下:
' [0-9]+\.'
[0-9]表示0到9范围内的任何数字。
答案 2 :(得分:0)
正则表达似乎是要走的路。我建议您阅读NSRegularExpression
。
以下是一个如何运作的例子:
NSError *regexError;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" [0-9]\." options:kNilOptions error:®exError];
if (regexError) {
// There was some sort of error when creating the regex.
}
NSUInteger numberOfMatches = [regex numberOfMatchesInString:yourTestString options:kNilOptions range:(NSRange){0, [yourTestString length]}];
if (numberOfMatches > 0) {
// There was a match
}