如何使用正则表达式查找以三个字符开头的单词 [英] How to use regular expressions to find words that begin with a three character prefix
问题描述
我的目标是计算以一个以上字母的指定前缀开头的单词(字符串中)的数量.一种情况是以"non"开头的单词.所以在这个例子中...
My goal is to count the number of words (in a string) that begin with a specified prefix of more than one letter. A case is words that begin with "non". So in this example...
NSString * theFullTestString = @"nonsense non-issue anonymous controlWord";
...我想在废话"和非问题"上获得成功,但在匿名"或"controlWord"上却没有获得成功.我的总点击数应为2.
...I want to get hits on "nonsense" and "non-issue", but not on "anonymous" or "controlWord". The total count of my hits should be 2.
所以这是我的测试代码,看起来似乎很接近,但是我尝试过的所有正则表达式都无法正常工作.此代码捕获废话"(正确)和匿名"(错误),但不捕获非问题"(错误).它的计数为2,但原因不正确.
So here's my test code which seems close, but none of the regular expression forms I've tried works correctly. This code catches "nonsense" (correct) and "anonymous" (wrong) but not "non-issue" (wrong). Its count is 2, but for the wrong reason.
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);
}
我很困惑.
推荐答案
正则表达式 \ bnon [\ w-] *
应该可以解决问题
The regex \bnon[\w-]*
should do the trick
\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);
}
这篇关于如何使用正则表达式查找以三个字符开头的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!