Monday, 18 September 2017

Return first match of Ruby regex




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



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"

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...