Return first match of Ruby regex

Return first match of Ruby regex

Asked on January 8, 2019 in Regex.
Add Comment


  • 2 Answer(s)

    Use variableName[/regular expression/].

    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"
    
    Answered on January 8, 2019.
    Add Comment

    Use below code if existence of a match is important:

    /regexp/ =~ "string"
    

    Use match return the first hit, while scan searches throughout entire string:

    matchData = "string string".match(/string/)
    matchData[0]   # => "string"
    matchData[1]   # => nil - it's the first capture group not a second match
    
    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.