Ruby Regexp group matching, assign variables on 1 line

前端 未结 5 852
旧巷少年郎
旧巷少年郎 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:19

    You don't want scan for this, as it makes little sense. You can use String#match which will return a MatchData object, you can then call #captures to return an Array of captures. Something like this:

    #!/usr/bin/env ruby
    
    string = "RyanOnRails: This is a test"
    one, two, three = string.match(/(^.*)(:)(.*)/i).captures
    
    p one   #=> "RyanOnRails"
    p two   #=> ":"
    p three #=> " This is a test"
    

    Be aware that if no match is found, String#match will return nil, so something like this might work better:

    if match = string.match(/(^.*)(:)(.*)/i)
      one, two, three = match.captures
    end
    

    Although scan does make little sense for this. It does still do the job, you just need to flatten the returned Array first. one, two, three = string.scan(/(^.*)(:)(.*)/i).flatten

提交回复
热议问题