Ruby Regexp group matching, assign variables on 1 line

前端 未结 5 847
旧巷少年郎
旧巷少年郎 2020-12-07 12:38

I\'m currently trying to rexp a string into multiple variables. Example string:

ryan_string = \"RyanOnRails: This is a test\"

I\'ve mat

5条回答
  •  遥遥无期
    2020-12-07 13:22

    scan() will find all non-overlapping matches of the regex in your string, so instead of returning an array of your groups like you seem to be expecting, it is returning an array of arrays.

    You are probably better off using match(), and then getting the array of captures using MatchData#captures:

    g1, g2, g3 = ryan_string.match(/(^.*)(:)(.*)/i).captures
    

    However you could also do this with scan() if you wanted to:

    g1, g2, g3 = ryan_string.scan(/(^.*)(:)(.*)/i)[0]
    

提交回复
热议问题