I'd like to split the following string:
user = "Lisa: yes"
So that I can get "Lisa"
Right now I have :
user[/([a-zA-Z].*?):/]
but it returns
"Lisa:"
How can I split the string so that it will return each letter up to the colon?
Thanks in advance!
You can use this: user.split(':').first
user = "Lisa: yes"
=> "Lisa: yes"
irb(main):006:0> user.split(':').first
=> "Lisa"
The split method will transform your string into an array, this array: ['Lisa',' yes']. Then, you'll just got to parse it with the first method, to get the first item, Lisa. Simple and intuitive, because personally, I hate regular expressions. I also like Arup Rakshit answer ;)
Do as below :
user = "Lisa: yes"
user[/([a-zA-Z].*?):/,1] # => "Lisa"
Documentation of str[regexp, capture] :
If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With