Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting A String Up To A Character

Tags:

regex

ruby

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!

like image 393
user3245240 Avatar asked Dec 02 '25 08:12

user3245240


2 Answers

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 ;)

like image 60
sidney Avatar answered Dec 04 '25 22:12

sidney


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.

like image 35
Arup Rakshit Avatar answered Dec 05 '25 00:12

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!