Reputation: 385
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!
Upvotes: 3
Views: 570
Reputation: 37419
This very simple regex will do (because the *
operator is greedy by default):
/-(.*)-/
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"
Upvotes: 7