From: Martin DeMello Date: 2002-12-01T16:42:01+09:00 Subject: Re: Regular expressions from the end of a string the Bare wrote: > Hi: > > Is there anyway to have a regular expression match from the end of a > string? I would like to match something like the following: > > TextThatIWantToMatchThatMayHaveNumbersAndHyphensInIt-0123.EXT > > The hyphen may or may not be there. For example, from > "TK-23-ab-355.bnd" I would want to find "TK-23-ab". > > Because, the text I want to match may have numbers in it, it seems to me > that I somehow have to match from the end of the string. I want to I've > tried expressions like the following: > > match = /^(.*)[^0-9]*[0-9]+\.(jpg|gif)$/i.match(filename) > > But it didn't work (of course!). Is there anyway to do what I want > without actually reversing the string? Since you want all the rest of the string, how about match = filename.gsub(/-?\d+\.(jpg|gif)$/,'') Or to match it with a regex, add a (.*?) in front match = /(.*?)-?\d+\.(jpg|gif)$/.match(filename) which will capture your string in match[1] The .*? is a non-greedy match, so it'll match only until the rest of the regex does. \d is the digit character class (saves writing [0-9]). The gsub's a lot more efficient, though. And here's the sexeger page I referred to earlier: http://japhy.perlmonk.org/sexeger/sexeger.html martin