rubyist
rubyist

Reputation: 3132

Match any string before end of a character

I have a date which returns either "23-12-2010" or '2013-' I want to extract the valid year for 2013- ie. 2013 and valid date for 23-12-1010 i.e 23-12-2010. So I am trying to extract all the tring before last '-' if it is present.

I tried like below.

"2013-"[/.+?(?=-)/]

But it returned only "23-12" for the date "23-12-2010" What am I missing here.??

Upvotes: 0

Views: 49

Answers (4)

seph
seph

Reputation: 6076

Use sub to remove the dash at the end:

"2013-".sub(/-\z/, "")
=> "2013" 

"23-12-2010".sub(/-\z/, "")
=> "23-12-2010" 

Upvotes: 0

steenslag
steenslag

Reputation: 80065

 p "23-12-2010".chomp('-') # => "23-12-2010"
 p '2013-'.chomp('-')      # => "2013"

Upvotes: 1

Raza Hussain
Raza Hussain

Reputation: 762

Its not good solution but i think it will work for you:

s="23-12-2010"
s.split('-').size==3 ? s.split('-').last : s.split('-').first
=> "2010"

s2="2010-"
s2.split('-').size==3 ? s2.split('-').last : s2.split('-').first
=> "2010"

Upvotes: 0

willis
willis

Reputation: 189

Seems like in your case the year contains 4 digit, so you can write something like:

2.1.5 :037 > "23-12-2010"[/\d{4}/]
 => "2010"

As you can see this regexp will detect year by 4 digits pattern.

Upvotes: 2

Related Questions