Regular Expressions

Flashcard 2 of 10

Given the following message, how can we most easily slice out all the usernames that are prefixed with an @ symbol?

The original idea came from @r00k, then @christoomey did a first pass, and @jferris came through to help clean up the implementation.

We can use the String#scan method to pull out all the matches for a given pattern into an array:

message = <<-MESSAGE
The original idea came from @r00k,
then @christoomey did a first pass,
and @jferris came through to help
clean up the implementation.
MESSAGE

username_pattern = /@\w+/

message.scan(username_pattern)
#=> ["@r00k", "@christoomey", "@jferris"]

Check out the docs for the scan method for more info.

Return to Flashcard Results