0

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"]
victorhazbun
  • 786
  • 8
  • 16

4 Answers4

3

Use look behind

(?<=@)\w+

this will leave @ symbol regex

Nambi_0915
  • 1,091
  • 8
  • 21
  • At the moment this is the best answer which fulfils the requirements. Can you please explain the `?<=` in the regex? Thank you. – victorhazbun Sep 19 '18 at 06:54
  • 1
    `?<=` is the look behind operator. It matches from the character next to it and not itself. `\w+` will match the words or digits continuously without any space or anyother special characters – Nambi_0915 Sep 19 '18 at 06:57
  • 2
    Best to be precise. `(?<=@)` is a *positive* look-behind expression. It means that the string `"@"` must immediately precede the match that follows, but is not part of the match. `\w+` matches a sequence of one or more *word characters*, namely, letters (uppercase or lowercase), digits or underscores (`"_"`). – Cary Swoveland Sep 19 '18 at 07:20
1

I would go with:

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

You might want to read about look-behind regexp.

spickermann
  • 100,941
  • 9
  • 101
  • 131
1

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

@(\w+)

username_pattern = /@(\w+)/

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Try this

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