victorhazbun
victorhazbun

Reputation: 841

Ruby regular expression to get users names after @ symbol

How can I get the username without the @ symbol? That's everything between @ and any non-word character.

message = <<-MESSAGE
From @victor with love,
To @andrea,
and CC goes to @ghost
MESSAGE

Using a Ruby regular expression, I tried

username_pattern = /@\w+/

I will like to get the following output

message.scan(username_pattern)
#=> ["victor", "andrea", "ghost"]

Upvotes: 0

Views: 309

Answers (4)

anjali rai
anjali rai

Reputation: 195

Try this

irb(main):010:0> message.scan(/@(\w+)/m).flatten
=> ["victor", "andrea", "ghost"]

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

You could match the @ and then capture one or more times a word character in a capturing group

@(\w+)

username_pattern = /@(\w+)/

Regex demo

Upvotes: 1

spickermann
spickermann

Reputation: 106932

I would go with:

message.scan(/(?<=@)\w+/)
#=> ["victor","andrea","ghost"]

You might want to read about look-behind regexp.

Upvotes: 1

Nambi_0915
Nambi_0915

Reputation: 1091

Use look behind

(?<=@)\w+

this will leave @ symbol regex

Upvotes: 3

Related Questions