Regular expression in ruby to match the text between first occurrence and last occurrence of a character

regex, ruby

Solution

This very simple regex will do (because the `*` operator is greedy by default):

/-(.*)-/

http://regex101.com/r/yZ7rI5

In ruby:

'ruby-on-rails'[/-(.*)-/, 1]
# => "on" 
'abc-def-ghi-jkl'[/-(.*)-/, 1]
# => "def-ghi"
'mnop-qrst-uvw-xyza-bc-defg-hij-123'[/-(.*)-/, 1]
# => "qrst-uvw-xyza-bc-defg-hij"

Problem

Can anyone help me to form a regular expression in ruby that would match the text between first occurrence and last occurrence of a character. For example, for the character `-`: ruby-on-rails should get result --> on abc-def-ghi-jkl should get result --> def-ghi mnop-qrst-uvw-xyza-bc-defg-hij-123 should get result --> qrst-uvw-xyza-bc-defg-hij Thoughts appreciated!

Original source