given a string as follow:
randomstring1-randomstring2-3df83eeff2
How can I use a ruby regex or some other ruby/r开发者_运维问答ails friendly method to find everything up until the first dash -
In the example above that would be: randomstring1
Thanks
You can use this pattern: ^[^\-]*
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 -
.
Using irb you can do this too:
>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>>
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.
精彩评论