Reputation: 5320
given a string as follow:
randomstring1-randomstring2-3df83eeff2
How can I use a ruby regex or some other ruby/rails friendly method to find everything up until the first dash -
In the example above that would be: randomstring1
Thanks
Upvotes: 22
Views: 27969
Reputation: 27913
mystring = "randomstring1-randomstring2-3df83eeff2"
firstPart = mystring[0, mystring.index("-")]
Otherwise, I think the best regex is @polishchuk's.
It matches from the beginning of the string, matches as many as possible of anything that is not a dash -
.
Upvotes: 9
Reputation: 461
Using irb you can do this too:
>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>>
Upvotes: 8
Reputation: 41222
For this situation, the index solution given by agent-j is probably better. If you did want to use regular expressions, the following non-greedy (specified by the ?
) regex would grab it:
(^.*?)-
You can see it in Rubular.
Upvotes: 3