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

25,889

Solution 1

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

Solution 2

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 -.

Solution 3

Using irb you can do this too:

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

Solution 4

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.

Share:
25,889
TheExit
Author by

TheExit

Updated on July 01, 2020

Comments

  • TheExit
    TheExit almost 4 years

    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

  • JBB
    JBB almost 13 years
    Tsk...Extra backslash. :) Dash doesn't need to be escaped when it's the first character in a character class (the opening caret doesn't count as a character in the class, it's a class modifier, specifically meaning "Not" as in "Not any of these characters in this class"
  • Kirill Polishchuk
    Kirill Polishchuk almost 13 years
    @JBB, I agree, my habit... :-)
  • Brad
    Brad over 9 years
    Could you explain why this works? I didn't realize you could use the caret twice.
  • Kirill Polishchuk
    Kirill Polishchuk over 9 years
    @Brad, 1st caret is "beginning of the string". [^\-] means any character except -.
  • Brad
    Brad over 9 years
    @KirillPolishchuk Thanks, I understand the beginning of a string part but I don't understand how it's used twice here. Does this mean that [^\-]* means any string that doesn't start with -?
  • Kirill Polishchuk
    Kirill Polishchuk over 9 years
    @Brad,no, it will just grab first matching string. Try to remove the first ^. In this case reges matches randomstring1, randomstring2 and 3df83eeff2