Return first match of Ruby regex

You can use []: (which is like match)

"[email protected]"[/\+([^@]+)/, 1] # matches capture group 1, i.e. what is inside ()
# => "account2"
"[email protected]"[/\+([^@]+)/]    # matches capture group 0, i.e. the whole match
# => "+account2"

You could try String#[] (as in variableName[/regular expression/]).

This is an example output from IRB:

names = "erik kalle johan anders erik kalle johan anders"
# => "erik kalle johan anders erik kalle johan anders"
names[/kalle/]
# => "kalle"

Tags:

String

Ruby

Regex