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
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" .
To find all the matching strings, use String's scan method.
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)
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 "(" .
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 -
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With