6

我的目标是计算以多个字母的指定前缀开头的单词(在字符串中)的数量。格是以“非”开头的词。所以在这个例子中......

NSString * theFullTestString = @"nonsense non-issue anonymous controlWord";

...我想获得关于“废话”和“非问题”的点击,而不是关于“匿名”或“controlWord”的点击。我的点击总数应该是 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);
}

我难住了。

4

3 回答 3

5

正则表达式\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

所以,在你的情况下:

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);
}
于 2013-02-06T22:04:33.743 回答
1

我认为正则表达式在这里有点矫枉过正。

NSString *words = @"nonsense non-issue anonymous controlWord";
NSArray *wordsArr = [words componentsSeparatedByString:@" "];
int count = 0;
for (NSString *word in wordsArr) {
    if ([word hasPrefix:@"non"]) {
        count++;
        NSLog(@"%dth match: %@", count, word);
    }
}

NSLog(@"Count: %d", count);
于 2013-02-06T22:02:55.720 回答
0

有更简单的方法可以做到这一点。您可以使用 NSPredicate 并使用此格式 BEGINSWITH[c] %@。

示例代码

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"Firstname BEGINSWITH[c] %@", text];
NSArray *results = [People filteredArrayUsingPredicate:resultPredicate];
于 2014-10-31T18:09:22.247 回答