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)

4

2 回答 2

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​​ 正则表达式的知识

于 2013-06-16T03:02:22.800 回答
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"

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

于 2013-06-16T02:28:32.140 回答