Han*_*Han 5 regex ios nsregularexpression
我的目标是计算以多个字母的指定前缀开头的单词数(以字符串形式).案例是以"非"开头的单词.所以在这个例子中......
NSString * theFullTestString = @"nonsense non-issue anonymous controlWord";
Run Code Online (Sandbox Code Playgroud)
......我想,但不是"匿名"或"控制字""胡说"和"不是问题的问题"命中.我的点击总数应为2.
所以这是我的测试代码似乎很接近,但我试过的正则表达式形式都没有正常工作.此代码捕获"废话"(正确)和"匿名"(错误)但不"非问题"(错误).它的数量是2,但出于错误的原因.
NSUInteger countOfNons = 0;
NSString * theFullTestString = @"nonsense non-issue anonymous controlWord";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"non(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:theFullTestString options:0 range:NSMakeRange(0, theFullTestString.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [theFullTestString substringWithRange:wordRange];
++countOfNons;
NSLog(@"Found word:%@ countOfNons:%d", word, countOfNons);
}
Run Code Online (Sandbox Code Playgroud)
我很难过.
正则表达式\bnon[\w-]*
应该做的伎俩
\bnon[\w-]*
^ (\b) Start of word
^ (non) Begins with non
^ ([\w-]) A alphanumeric char, or hyphen
^ (*) The character after 'non' zero or more times
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下:
NSUInteger countOfNons = 0;
NSString * theFullTestString = @"nonsense non-issue anonymous controlWord";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\bnon[\\w-]*)" options:0 error:&error];
NSArray *matches = [regex matchesInString:theFullTestString options:0 range:NSMakeRange(0, theFullTestString.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [theFullTestString substringWithRange:wordRange];
++countOfNons;
NSLog(@"Found word:%@ countOfNons:%d", word, countOfNons);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2655 次 |
最近记录: |