我需要使用rails / ruby从字符串中提取所有@usernames(对于twitter):
String Examples:
"@tom @john how are you?"
"how are you @john?"
"@tom hi"
该函数应该从字符串中提取所有用户名,并且不允许用户名不允许使用特殊字符......如您所见“?”在一个例子......
答案 0 :(得分:1)
有多种方法可以做到 - 这是一种方式:
string = "@tom @john how are you?"
words = string.split " "
twitter_handles = words.select do |word|
word.start_with?('@') && word[1..-1].chars.all? do |char|
char =~ /[a-zA-Z1-9\_]/
end && word.length > 1
end
char =~
正则表达式只接受alphaneumerics和下划线
答案 1 :(得分:1)
["tom", "john", "andré"]
如果您希望返回
@
将正则表达式的第一行从(?<=@)
更改为
"@"
这是一个积极的外观。它要求角色print $d_quote . join("$d_quote$comma$d_quote", @total) . $d_quote;
存在,但不会成为比赛的一部分。
答案 2 :(得分:1)
来自&#34; Why can't I register certain usernames?&#34;:
如上所述,用户名只能包含字母数字字符(字母A-Z,数字0-9),但下划线除外。检查以确保您所需的用户名不包含任何符号,短划线或空格。
\w
metacharacter is equivalent to [a-zA-Z0-9_]
:
/\w/
- 单词字符([a-zA-Z0-9_]
)
只需扫描@\w+
即可成功:
strings = [
"@tom @john how are you?",
"how are you @john?",
"@tom hi",
"@foo @_foo @foo_ @foo_bar @f123bar @f_123_bar"
]
strings.map { |s| s.scan(/@\w+/) }
# => [["@tom", "@john"],
# ["@john"],
# ["@tom"],
# ["@foo", "@_foo", "@foo_", "@foo_bar", "@f123bar", "@f_123_bar"]]