2012-11-30 144 views
0

我正在使用NSRegularExpression讀取文本並找出hashtag。 這是我在regularExpressionWithPattern中使用的NSString。NSRegularExpression ISSUE

- (NSString *)hashtagRegex 
{ 
    return @"#((?:[A-Za-z0-9-_]*))"; 
    //return @"#{1}([A-Za-z0-9-_]{2,})"; 

} 

這是我的方法:

// Handle Twitter Hashtags 
    detector = [NSRegularExpression regularExpressionWithPattern:[self hashtagRegex] options:0 error:&error]; 
    links = [detector matchesInString:theText options:0 range:NSMakeRange(0, theText.length)]; 
    current = [NSMutableArray arrayWithArray:links]; 

    NSString *hashtagURL = @"http://twitter.com/search?q=%23"; 
    //hashtagURL = [hashtagURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 

    for (int i = 0; i < [links count]; i++) { 

    NSTextCheckingResult *cr = [current objectAtIndex:i]; 

    NSString *url = [theText substringWithRange:cr.range]; 

    NSString *nohashURL = [url stringByReplacingOccurrencesOfString:@"#" withString:@""]; 
    nohashURL = [nohashURL stringByReplacingOccurrencesOfString:@" " withString:@""]; 

    [theText replaceOccurrencesOfString:url 
          withString:[NSString stringWithFormat:@"<a href=\"%@%@\">%@</a>", hashtagURL, nohashURL, url] 
           options:NSLiteralSearch 
            range:NSMakeRange(0, theText.length)]; 
    current = [NSMutableArray arrayWithArray:[detector matchesInString:theText options:0 range:NSMakeRange(0, theText.length)]]; 

    } 

    [theText replaceOccurrencesOfString:@"\n" withString:@"<br />" options:NSLiteralSearch range:NSMakeRange(0, theText.length)]; 

    [_aWebView loadHTMLString:[self embedHTMLWithFontName:[self fontName] 
                size:[self fontSize] 
                text:theText] 
        baseURL:nil]; 

一切工作,但它想出了一個小問題,當我使用這樣的字符串:

NSString * theText = @"#twitter #twitterapp #twittertag"; 

我的代碼只凸顯#twitter在每個單詞上,而不是它的第二部分(#twitter #twitter(app)#twitter(tag))。 我希望有人能幫助我!

謝謝:)

回答

0

聲明

[theText replaceOccurrencesOfString:url 
         withString:[NSString stringWithFormat:@"<a href=\"%@%@\">%@</a>", hashtagURL, nohashURL, url] 
          options:NSLiteralSearch 
           range:NSMakeRange(0, theText.length)]; 

正在取代字符串url與替換字符串的所有實例。在第一次通過循環的例子中,url@"#twitter",並且在theText內的該字符串的所有三次出現被一次性替換。這是theText看起來像那麼:

<a href="http://twitter.com/search?q=%23twitter">#twitter</a> <a href="http://twitter.com/search?q=%23twitter">#twitter</a>app <a href="http://twitter.com/search?q=%23twitter">#twitter</a>tag 

等等,當然,接下來的兩次一輪循環中,結果不是你所期望相當的...!

我認爲解決辦法是限制更換的範圍:你說得對,我完全心不在焉,我沒有注意到that..thank-你它像一個

[theText replaceOccurrencesOfString:url 
         withString:[NSString stringWithFormat:@"<a href=\"%@%@\">%@</a>", hashtagURL, nohashURL, url] 
          options:NSLiteralSearch 
           range:cr.range]; 
+0

魅力!! –