Ruby String split with regex

前端 未结 4 744
清酒与你
清酒与你 2021-01-03 23:16

This is Ruby 1.8.7 but should be same as for 1.9.x

I am trying to split a string for example:

a = \"foo.bar.size.split(\'.\').last\"         


        
4条回答
  •  春和景丽
    2021-01-03 23:38

    I think this would do it:

    a.split(/\.(?=[\w])/)
    

    I don't know how much you know about regex, but the (?=[\w]) is a lookahead that says "only match the dot if the next character is a letter kind of character". A lookahead won't actually grab the text it matches. It just "looks". So the result is exactly what you're looking for:

    > a.split(/\.(?=[\w])/)
     => ["foo", "bar", "size", "split('.')", "last"] 
    

提交回复
热议问题