Profanity list – Swift3

Adium pentru IOS are un plugin special pentru filtrarea cuvintelor urate – profanity list – care in schimb e foarte Objective C.
Am modelat in playground o clasa speciala de Regular Expression prin intermediul careia filtrez continutul unui dictionar. Ideea de baza este de aici

var badWordDictionary: [String : String] = [
"cuvant1" : "*******",
"cuvant2" : "*******",
"cuvant3" : "*******",
"cuvant4" : "*******",
"cuvant5" : "*******",
"cuvant6" : "*******",
]
var bannedWords = badWordDictionary.keys
var bannedPattern = bannedWords.joined(separator: "|")
var badWordPattern = "\\b(?:\(bannedPattern))\\b"

class MeetMeBadWordRegularExpression: NSRegularExpression {
override func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
let matchingRange = result.range
let matchingWord = (string as NSString).substring(with: matchingRange)
if let replacedWord = badWordDictionary[matchingWord] {
return replacedWord
} else {
return "*"
}
}
}

Apoi vom folosi astfel:

var bodyMessage = "acesta este cuvant1"
let regex = try! MeetMeBadWordRegularExpression(pattern: badWordPattern, options: [])
let clearBodyMessage = regex.stringByReplacingMatches(in: bodyMessage as! String, options: [], range: NSRange(0..<(bodyMessage as! String).utf16.count), withTemplate: "") print("clean message - \(clearBodyMessage)")

Vom avea clean message - acesta este *******

Share Button