我试图找到仅在当前光标位置替换@mention的正则表达式。使用以下正则表达式替换textView中可用的所有@mention。我也试过pattern = "\\s\\@[a-z]+\\s"
,但仍然失败了。
func replace() {
let pattern = "@[a-zA-Z0-9_.]+?(?![a-zA-Z0-9_.])"
let txt = textView.text
let length = textView.text.characters.count
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let newString = regex.stringByReplacingMatches(in: txt!, options: [], range: NSMakeRange(0, length), withTemplate: "@\(userName)")
textView.text = newString
}