我是swift的新手。我需要从单词列表中获得一个前缀为#
的字符串。这是我的字符串
“在6月14日的火灾之后,有30人被证实死亡,但预计总数会上升得更高。...一名男子在#Facebook上张贴了相信有人身体的照片从#Grenfell塔跳到他的死亡#fire已经#jiled了三个月“
我需要流动的单词列表:
["#Facebook","#Grenfell","#fire","#jailed"]
我花了很多时间但却无法弄清楚如何实现这一目标。
答案 0 :(得分:2)
您可以这样做:
let str = "Thirty people are confirmed dead after the June 14 fire, but the total is expected to rise far higher. ... A man who posted pictures on #Facebook of the body of someone believed to have leapt to his death from the #Grenfell Tower #fire has been #jailed for three months"
let words = str.components(separatedBy: " ").filter { (element) -> Bool in
return element.hasPrefix("#")
}
print(words)
答案 1 :(得分:0)
这是一个简单的解决方案:
逻辑:将文本拆分为单词数组,然后使用谓词对其进行过滤。
let stringText = "Thirty people are confirmed dead after the June 14 fire, but the total is expected to rise far higher. ... A man who posted pictures on #Facebook of the body of someone believed to have leapt to his death from the #Grenfell Tower #fire has been #jailed for three months"
let wordsArray = stringText.characters.split{$0 == " "}.map(String.init)
let filteredList = wordsArray.filter {NSPredicate(format:"SELF BEGINSWITH %@","#").evaluate(with: $0)}
答案 2 :(得分:0)
使用NSRegularExpression
过滤带有特定前缀的字符串 -
//Xcode 8.3 swift 3.x
var string: String = "Thirty people are confirmed dead after the June 14 fire, but the total is expected to rise far higher. ... A man who posted pictures on #Facebook of the body of someone believed to have leapt to his death from the #Grenfell Tower #fire has been #jailed for three months"
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches: [NSTextCheckingResult] = (regex?.matches(in: string, options: [], range: NSRange(location: 0, length: (string.characters.count ))))!
for match in matches {
let wordRange = (match).rangeAt(1)
let word = (string as NSString).substring(with: wordRange)
print("Found tag - \(word)")
}
// Objective c ->
NSString*string = @"Thirty people are confirmed dead after the June 14 fire, but the total is expected to rise far higher. ... A man who posted pictures on #Facebook of the body of someone believed to have leapt to his death from the #Grenfell Tower #fire has been #jailed for three months";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [string substringWithRange:wordRange];
NSLog(@"Found tag %@", word);
}