Using Ruby... given the following string:
x = "blah_blah.do.dah[4543]junk_junk"
How do I remove all text after the last number/digit?
I thought the easiest way to do this might be by finding the index of last occurrence and then removing everything after that index. However, I can't seem to figure out how to obtain that index. All my attempts at using regex have failed.
There are answers how to do what you need
Also to find last occurence of number:
x = 'blah_blah.do.dah[4543]junk_junk'
x.rindex(/\d/)
This may be the regex you're looking for:
s/\D*$//
This regex matches all non-digits at the end of the string, starting from the last digit or the start of the string (if it doesn't contain any digits at all), and removes whatever is matched. More precisely, \D*
is a greedy match for as many non-digits as possible (zero or more). $
represents the end of the string.
In Ruby you can use the gsub method of a string to search and replace using a regular expression:
x = 'blah_blah.do.dah[4543]junk_junk'
y = x.gsub(/\D*$/, '')
For more info on regexes and Ruby, see regular-expressions.info.
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