Katie H
Katie H

Reputation: 2293

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'].

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". How do I get this to work?

Upvotes: 1

Views: 66

Answers (4)

Andrii Furmanets
Andrii Furmanets

Reputation: 1161

Or this one:

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

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118299

Another way :

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

Upvotes: 2

toro2k
toro2k

Reputation: 19238

You are somewhat reinventing the wheel, the String#scan method is here for exactly your purpose:

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

Update: Given that the usernames string always has the exact format you described, i.e. it contains just @-prefixed usenames, commas, and spaces; the regexp can be made a little simpler:

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

Upvotes: 4

sawa
sawa

Reputation: 168269

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"]

Upvotes: 3

Related Questions