Reputation: 2920
I wanna know if there is a quick way to solve the problem in ruby like example below
example "t12" => text="t", value=12
"ad15" => text = "ad", value = 15
"acbds1687" => text = "acbds", value=1687
I think regular expression may can solve this but I am not sure about regular expression.
Upvotes: 1
Views: 134
Reputation: 13901
If you give create a capture group it stays in the split, thus this code is pretty slick:
text, value = string.split(/(\d+)/)
or you can use the slice! method:
text = 'sagasg125512'
value = text.slice!(/\d+/)
p text #=> "sagasg"
p value #=> "125512"
Upvotes: 2
Reputation: 13612
To parse the string into a hash like { :text => "t", :value => 12 }
:
def parse (string)
matchdata = string.match(/([a-zA-Z]+)([\d]+)/)
text = matchdata[1]
value = matchdata[2].to_i
return { text: text, value: value }
end
To parse the string into an array like ["t", 12]
:
def parse (string)
matchdata = string.match(/([a-zA-Z]+)([\d]+)/)
text = matchdata[1]
value = matchdata[2].to_i
return [text, value]
end
Upvotes: 1
Reputation: 160833
Like below:
irb(main):001:0> "t12".split(/(?<=[a-zA-Z])(?=\d)/)
=> ["t", "12"]
Upvotes: 2