tags:

views:

1194

answers:

2

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
+4  A: 

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"
Presidenten
Is this not doing a match and returning the first result behind the scenes ?
Gishu
After some benchmarking with various length strings and looking at the C source, it turns out Regex.match does short-circuit and only finds the first match.
Daniel Beardsley
+2  A: 

If only an existence of a match is important, you can go with

/regexp/ =~ "string"

Either way, match should only return the first hit, while scan searches throughout entire string. Therefore if

matchData = "string string".match(/string/)
matchData[0]    # => "string"
matchData[1]    # => nil - it's the first capture group not a second match
Slartibartfast