简体   繁体   English

正则表达式以匹配以“ @”字符为前缀的用户名

[英]Regexp to match usernames prefixed by “@” character

I'm trying to write a method that takes a string that's inputted through a form with the following format: 我正在尝试编写一个方法,该方法采用通过以下格式的表单输入的字符串:

string = "@user1, @user2, @user3"

And returns an array like ['user1', 'user2', 'user3'] . 并返回类似['user1', 'user2', 'user3']的数组。

This is what I have so far: 这是我到目前为止的内容:

usernames = "@user1, @user2"

temp_recipient_usernames = usernames.split(',')
recipient_usernames = temp_recipient_usernames.each do |u|
  u.gsub /@(\w+)/ do |username|
    @final_usernames = username.gsub('@', '')
  end
end

p @final_usernames

This only returns the string "user2" . 这仅返回字符串"user2" How do I get this to work? 我该如何工作?

You are somewhat reinventing the wheel, the String#scan method is here for exactly your purpose: 您正在重新设计轮子,这里的String#scan方法正是出于您的目的:

usernames = "@user1, @user2"
usernames.scan(/(?<=@)\w+/)
# => ["user1", "user2"]

Update : Given that the usernames string always has the exact format you described, ie it contains just @ -prefixed usenames, commas, and spaces; 更新 :假设usernames字符串始终具有您描述的确切格式,即它仅包含@前缀的使用名,逗号和空格; the regexp can be made a little simpler: 可以将regexp简化一些:

usernames.scan(/\w+/)
# => ["user1", "user2"]

This is not the shortest way, but is conceptually straightforward. 这不是最短的方法,但是在概念上很简单。

"@user1, @user2, @user3"
.split(", ")
.map{|s| s.delete("@")}
# => ["user1", "user2", "user3"]

Or, 要么,

"@user1, @user2, @user3"
.delete("@")
.split(", ")
# => ["user1", "user2", "user3"]

Another way : 其他方式 :

usernames = "@user1, @user2"
usernames.split(/\W/).reject(&:empty?) # => ["user1", "user2"]

Or this one: 或者这个:

"@user1, @user2, @user3".gsub("@","").split(",")
#=> ["user1", " user2", " user3"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM