我有一个基于Swift的iOS应用程序,其中一个功能允许您对帖子发表评论。无论如何,用户可以在帖子中添加“@mentions”来标记其他人。但是,我想阻止用户添加带有大写字母的用户名。
无论如何我可以转换一个字符串,以便@usernames都是小写的吗?
例如:
我非常喜欢观看@uSerABC(不允许)
我非常喜欢@userabc(允许)观光
我知道swift中有一个名为.lowercaseString
的字符串的属性 - 但问题是,它使整个字符串小写,这不是我想要的。我只希望@username为小写。
有必要使用.lowercase
属性吗?
谢谢你的时间,Dan。
答案 0 :(得分:1)
这来自我用来检测主题标签的代码,我已修改以检测提及:
func detectMentionsInText(text: String) -> [NSRange]? {
let mentionsDetector = try? NSRegularExpression(pattern: "@(\\w+)", options: NSRegularExpressionOptions.CaseInsensitive)
let results = mentionsDetector?.matchesInString(text, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, text.utf16.count)).map { $0 }
return results?.map{$0.rangeAtIndex(0)}
}
它通过使用正则表达式检测字符串中的所有提及并返回一个NSRange数组,使用一个范围,你有"提及"你可以用小写版本轻松替换它们。
答案 1 :(得分:0)
使用以下命令将字符串拆分为两个 -
let arr = myString.componentsSeparatedByString("@")
//Convert arr[1] to lower case
//Append to arr[0]
//Enjoy
答案 2 :(得分:0)
感谢大家的帮助。最后,我无法获得任何解决方案,经过大量测试后,我想出了这个解决方案:
func correctStringWithUsernames(inputString: String, completion: (correctString: String) -> Void) {
// Create the final string and get all
// the seperate strings from the data.
var finalString: String!
var commentSegments: NSArray!
commentSegments = inputString.componentsSeparatedByString(" ")
if (commentSegments.count > 0) {
for (var loop = 0; loop < commentSegments.count; loop++) {
// Check the username to ensure that there
// are no capital letters in the string.
let currentString = commentSegments[loop] as! String
let capitalLetterRegEx = ".*[A-Z]+.*"
let textData = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
let capitalResult = textData.evaluateWithObject(currentString)
// Check if the current loop string
// is a @user mention string or not.
if (currentString.containsString("@")) {
// If we are in the first loop then set the
// string otherwise concatenate the string.
if (loop == 0) {
if (capitalResult == true) {
// The username contains capital letters
// so change it to a lower case version.
finalString = currentString.lowercaseString
}
else {
// The username does not contain capital letters.
finalString = currentString
}
}
else {
if (capitalResult == true) {
// The username contains capital letters
// so change it to a lower case version.
finalString = "\(finalString) \(currentString.lowercaseString)"
}
else {
// The username does not contain capital letters.
finalString = "\(finalString) \(currentString)"
}
}
}
else {
// The current string is NOT a @user mention
// so simply set or concatenate the finalString.
if (loop == 0) {
finalString = currentString
}
else {
finalString = "\(finalString) \(currentString)"
}
}
}
}
else {
// No issues pass back the string.
finalString = inputString
}
// Pass back the correct username string.
completion(correctString: finalString)
}
它当然不是最优雅或最有效的解决方案,但确实有效。如果有任何改进方法,请发表评论。