MIZ
MIZ

Reputation: 385

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

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

Answers (3)

user3638280
user3638280

Reputation: 49

'ruby-on-rails'.scan(/-(.*)-/).first.first

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37419

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"

Upvotes: 7

Pedro Lobito
Pedro Lobito

Reputation: 99041

This will do it:

result = subject.scan(/-(.*)-/)

Upvotes: 0

Related Questions