TheExit
TheExit

Reputation: 5320

ruby regex - how to match everything up till the character -

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

Answers (4)

agent-j
agent-j

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

patsanch
patsanch

Reputation: 461

Using irb you can do this too:

>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>> 

Upvotes: 8

Mark Wilkins
Mark Wilkins

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

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

You can use this pattern: ^[^\-]*

Upvotes: 46

Related Questions