Return first match of Ruby regex

Daniel Beardsley picture Daniel Beardsley · Feb 6, 2009 · Viewed 74.9k times · Source

I'm looking for a way to perform a regex match on a string in Ruby and have it short-circuit on the first match.

The string I'm processing is long and from what it looks like the standard way (match method) would process the whole thing, collect each match, and return a MatchData object containing all matches.

match = string.match(/regex/)[0].to_s

Answer

Presidenten picture Presidenten · Feb 6, 2009

You could try variableName[/regular expression/]. This is an example output from irb:

irb(main):003:0> names = "erik kalle johan anders erik kalle johan anders"
=> "erik kalle johan anders erik kalle johan anders"
irb(main):004:0> names[/kalle/]
=> "kalle"