2016-09-26 40 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: "") 
    } 
}