用于标签的NSRegularExpression和带有特殊字符的提及? [英] NSRegularExpression for hashtags and mentions with special characters?
问题描述
我正在使用以下正则表达式来检测我的应用中的主题标签和提及。
I'm using the following regex expression to detect hashtags and mentions in my app.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#|@)(\\w+)" options:NSRegularExpressionCaseInsensitive error:&error];
但我的应用程序中的用户可以在其用户名中使用一些特殊字符。例如 @ user.name
或 @user_name
。不允许有空格。但是,使用thins正则表达式只会检测 @user
,而实际上它应该是 @ user.name
。人质工作完美,但用户名中的特殊字符打破了提及功能。
However users within my app are allowed to use some special characters in their usernames. For example @user.name
or @user_name
. Spaces are not allowed. However using thins regular expression would only detect @user
when it should in fact be @user.name
. Hostages work perfectly but the special characters in usernames break the mention functionality.
我真的很新的正则表达式,我不知道我需要改变什么才能解决这个问题。我很确定它可以做什么 \\\\ + + / c $ c>但是我可以做些什么帮助。
I'm really new to regex and I'm not sure what I need to change to fix this. I'm pretty sure its something to do \\w+
but what exactly I could do with some help.
推荐答案
因为您需要在 @
或#$ c $之后匹配任何非空格字符c>但是这个序列的最后一个字符必须是单词字符,你可以安全地使用
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).
-
[#@]
- 匹配#
或@
,1次 -
\S + \ b
- 匹配1个或多个非空白字符但是最后一个必须是边界一词。
[#@]
- match a#
or@
, 1 time\S+\b
- match 1 or more non-whitespace characters but the last one must be at the word boundary.
一个更强化的版本(以确保第一个chara cter #
/ @
是一个单词字符,整个用户名长度至少为1个字符):
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"
请注意此第二版不支持 @ - nick.name -
等名称。
Note that this second version will not support such names as @-nick.name-
.
这篇关于用于标签的NSRegularExpression和带有特殊字符的提及?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!