我是新來的swift。我需要得到的單詞列表形式是一個字符串,其前綴爲#
。這裏是我的字符串獲取字符串中的單詞列表
「三十人是在6月14日發生火災後確認死亡,但總預期上升得多。......一個人誰貼的圖片上#Facebook有人認爲身體已躍居從#Grenfell塔#fire他去世已經#jailed三個月」
我需要流動詞的列表:
["#Facebook","#Grenfell","#fire","#jailed"]
我花的時間很多,但無法弄清楚如何實現這一點。
我是新來的swift。我需要得到的單詞列表形式是一個字符串,其前綴爲#
。這裏是我的字符串獲取字符串中的單詞列表
「三十人是在6月14日發生火災後確認死亡,但總預期上升得多。......一個人誰貼的圖片上#Facebook有人認爲身體已躍居從#Grenfell塔#fire他去世已經#jailed三個月」
我需要流動詞的列表:
["#Facebook","#Grenfell","#fire","#jailed"]
我花的時間很多,但無法弄清楚如何實現這一點。
你可以做到這一點是:
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)
下面是簡單的解決方案:
邏輯:拆分文本字的數組,然後用謂詞過濾。
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)}
使用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);
}
的可能的複製過濾字符串[夫特:分割字符串到一個數組(https://stackoverflow.com/questions/25678373/ swift-split-a-string-into-an-an-array) – Lepidopteron