Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 740
TheExit Avatar asked Jun 30 '11 17:06

TheExit


People also ask

How do you match anything up until this sequence of characters in regular expression?

If you add a * after it – /^[^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a , or b , or c . For example, with the source string "qwerty qwerty whatever abc hello" , the expression will match up to "qwerty qwerty wh" .

What method should you use when you want to get all sequences matching a regexp pattern in a string?

To find all the matching strings, use String's scan method.

What is full match in regex?

The fullmatch() function returns a Match object if the whole string matches the search pattern of a regular expression, or None otherwise. The syntax of the fullmatch() function is as follows: re.fullmatch(pattern, string, flags=0)

How do you match a sequence in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .


2 Answers

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

like image 118
Kirill Polishchuk Avatar answered Oct 08 '22 20:10

Kirill Polishchuk


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

like image 32
agent-j Avatar answered Oct 08 '22 20:10

agent-j