NSRegularExpression for hashtags and mentions with special characters?

邮差的信 提交于 2019-12-04 17:40:13

Since you need to match any non-whitespace characters after @ or # but the last character of this sequence must be a word character, you can safely use

@"[#@]\\S+\\b"

Note that an alternative group (#|@) works more effeciently when transformed into a character class [#@] (it involves less backtracking).

Regex breakdown:

  • [#@] - match a # or @, 1 time
  • \S+\b - match 1 or more non-whitespace characters but the last one must be at the word boundary.

A bit more enhanced version (to make sure the first character after #/@ is a word character and the whole username is at least 1 character long):

@"[#@]\\w\\S*\\b"

Note that this second version will not support such names as @-nick.name-.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!