2016-09-26 39 views
2

我想要檢測以#開頭的單詞,並返回其特定範圍。起初,我嘗試使用下面的代碼:如何獲取特定子串的範圍(即使重複)

for word in words { 
    if word.hasPrefix("#") { 
     let matchRange = theSentence.range(of: word) 
     //Do stuff with this word 
    } 
} 

這工作得很好,但如果你有一個重複的主題標籤,將返回的主題標籤中第一次出現的範圍。這是因爲range(_:)函數的性質。

說我有以下字符串:

"The range of #hashtag should be different to this #hashtag" 

這將返回(13, 8)兩個井號標籤的時候,確實它應該返回(13, 8)以及(50, 8)。這怎麼解決?請注意,emojis也應該能夠在哈希標籤中被檢測到。

編輯

如果你想知道如何做到這一點使用表情符號來,去here

+0

你應該忽略最後發現#和字符串超出最後發現'hastag'所以它會消除最後的位置,你查詢應該是'而(theSentence.range(作者:!「#」)=無)' – iphonic

+0

如果你打算使用正則表達式,那麼這可能會有所幫助:http://stackoverflow.com/a/27880748/1187415,它正確處理所有Unicodes(Emojis,flags,...)。 –

回答

8

對於創建正則表達式,並與NSRegularExpression使用它,並找到匹配的範圍。

var str = "The range of #hashtag should be different to this #hashtag" 
let regex = try NSRegularExpression(pattern: "(#[A-Za-z0-9]*)", options: []) 
let matches = regex.matchesInString(str, options:[], range:NSMakeRange(0, str.characters.count)) 
for match in matches { 
    print("match = \(match.range)") 
} 
+0

這將與標籤中的表情符號一起使用嗎? – Tometoyou

+0

不,它不會與表情符號一起使用。 –

+0

啊,我需要它在標籤中使用emojis – Tometoyou

0

你爲什麼不把你的詞分成大塊,每個塊都以#開始。然後你就可以知道你的單詞有多少次出現在句子中。

編輯:我認爲,正則表達式的答案是最好的方式,但這是同樣的解決方案的其他方法。

var hastagWords = [""] 
for word in words { 
    if word.hasPrefix("#") { 
     // Collect all words which begin with # in an array 
     hastagWords.append(word) 
    } 
} 

// Create a copy of original word since we will change it 
var mutatedWord = word.copy() as! String 

for hashtagWord in hastagWords { 
    let range = mutatedWord.range(of: hashtagWord) 

    if let aRange = range { 
     // If range is OK then remove the word from original word and go to an other range 
     mutatedWord = mutatedWord.replacingCharacters(in: aRange, with: "") 
    } 
}