code_junkie

Return first match of Ruby regex

Nov 14th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.39 KB | None | 0 0
  1. match = string.match(/regex/)[0].to_s
  2.  
  3. irb(main):003:0> names = "erik kalle johan anders erik kalle johan anders"
  4. => "erik kalle johan anders erik kalle johan anders"
  5. irb(main):004:0> names[/kalle/]
  6. => "kalle"
  7.  
  8. /regexp/ =~ "string"
  9.  
  10. matchData = "string string".match(/string/)
  11. matchData[0] # => "string"
  12. matchData[1] # => nil - it's the first capture group not a second match
Add Comment
Please, Sign In to add comment