Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find last occurrence of a number in a string using Ruby?

Tags:

string

regex

ruby

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.

like image 856
Chadwick Avatar asked Oct 17 '09 14:10

Chadwick


2 Answers

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/)
like image 115
tig Avatar answered Sep 21 '22 21:09

tig


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.

like image 31
Stephan202 Avatar answered Sep 23 '22 21:09

Stephan202