如何在当前光标位置创建正则表达式@mention

时间:2017-09-26 09:14:23

标签: ios regex swift uitextview

我试图找到仅在当前光标位置替换@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

}

0 个答案:

没有答案