2017-03-31 38 views
-1

因此,我正在閱讀來自twitter bot的最新tweet並將其分配給字符串,但有時會直接向用戶發送推文。這是一個可能看起來像什麼的例子。從「N」字符串中刪除「@」和「:」之間的文本,同時保留後面的文本

NSString tweet = @("@user hey heres my message: BLah blah with symbols!"); 
//part I want to keep is: " BLah blah with symbols!" 
//or it could end up being 

NSString tweet = @("@otheruser my msg is: Wow heres some more blah: and a second colon"); 
//part I want to keep is: " Wow heres some more blah: and a second colon" 

我想始終刪除與用戶交談的第一部分,同時保留消息到最後。有太多不同的消息要使用「stringByReplacingOccurrencesOfString」

我不想使用twitter API的「exlude-reply」,因爲這個bot非常受歡迎,並且需要將「count」應用到100以上之前

任何想法如何做到這一點?我認爲這與正則表達式有關,但我之前從未使用過它們,或者能夠按照我的想法獲得一種工作方式。我真的很感激任何人的幫助衛生組織舒適的正則表達式

編輯:另外,如果一個正則表達式不會爲這種情況下工作,ID接受限制防止解釋,即:)

回答

1

最簡單的解決方案,我可以想到的是通過使用NSString函數componentsSeparatedBy:@":"創建一個NSMutable數組,並簡單地刪除第一個元素。

NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]]; 
[tweetArray removeObjectAtIndex:0]; 

你用冒號隨機事後出現問題可以通過再次一起加入件固定。

tweet = [tweetArray componentsJoinedByString:@":"]; 

編輯:修正了一個錯誤的用戶馬迪'

你必須在if語句要堅持這個代碼,以便它不執行有一個冒號正常鳴叫指出。但是,您可以使用始終以@user開頭的事實。

if ([tweet characterAtIndex:0] == '@' && [tweet characterAtIndex:1] != ' '){ 
    NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]]; 
    [tweetArray removeObjectAtIndex:0]; 

    tweet = [tweetArray componentsJoinedByString:@":"]; 
} 
+1

這不適用於諸如「請從此消息中刪除:」這樣的消息。 – rmaddy

+1

@maddy,我不明白你的意見。 – Graytr

+0

您的代碼將導致「來自此消息」。 – rmaddy

0

您也可以使用它。

NSString *myString = @"@username is me: by using this as sample text"; 
    NSRange range = [myString rangeOfString:@":"]; 
    NSString *newString= [myString substringFromIndex:range.location]; 
    NSLog(@"New String is : %@", newString); 
相關問題