如何使用正则表达式获取用户?

时间:2013-06-16 02:17:15

标签: ruby-on-rails ruby regex ruby-on-rails-3

例如,用户输入@John_Smith hi, what's up!? 我想打电话给John_Smith,并通知他让他注意 我该如何存档?

username = @comment ??????(I have no idea how to code it here)
@user = User.find_by_username(username)
current_user.send_message(@user, body, subject)

判断方式是@username(one space)

2 个答案:

答案 0 :(得分:1)

username = @comment.scan(/(?<=^@)\w+(?=[\s|~])/).first

控制台测试:

2.0.0-p195 :001 > s = "@John_Smith~hi"
 => "@John_Smith~hi"
2.0.0-p195 :002 > s.scan(/(?<=^@)\w+(?=[\s|_])/).first
 => "John_Smith"

编辑:现在接受~或空格作为分隔符。

答案 1 :(得分:1)

匹配字符串中的任何位置:

s.scan(/\@(\w+)/).flatten.first

样品:

>> s
"Hello @Jhon!"

>> s.scan(/\@(\w+)/).flatten.first
"Jhon"

>> s = "@John_Smith hi, what's up!?"
"@John_Smith hi, what's up!?"

>> s.scan(/\@(\w+)/).flatten.first
"John_Smith"

您可能希望http://www.rubular.com了解有关ruby正则表达式的更多信息