2013-02-06 67 views
5

我的目標是計算以多個字母的指定前綴開頭的單詞數量(以字符串形式)。一個案例是以「非」開頭的單詞。所以在這個例子...如何使用正則表達式來查找以三個字符前綴開頭的單詞

NSString * theFullTestString = @"nonsense non-issue anonymous 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); 
} 

我很難過。

回答

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); 
} 
+1

+1 OP不說,但考慮'NSRegularExpressionCaseInsensitive'如果混合的情況下將被視爲匹配。也可能是'NSRegularExpressionUseUnicodeWordBoundaries'。 – Rob

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); 
0

有更簡單的方法來做到這一點。您可以使用NSPredicate並使用此格式BEGINSWITH [c]%@。

示例代碼

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"Firstname BEGINSWITH[c] %@", text]; 
NSArray *results = [People filteredArrayUsingPredicate:resultPredicate]; 
相關問題