AaronDT AaronDT - 8 months ago 35
Ruby Question

Extract year from string, check if successful

I would like to check whether a year was found within a string. Something like

if string.scan(/\d{4}/).first == TRUE

for example a string looks like "there were 3 earthquakes in 2007"

Any suggestions?


If you want to match standalone 4 digit string, you may consider a regex with word boundaries:

!('It is 2016 now.' =~ /\b\d{4}\b/).nil? # => true

or - a more real world sample usage:

if string =~ /\b\d{4}\b/ 

The \b\d{4}\b matches any 4 digits that are not preceded nor followed with word characters (digits, letters or underscore), so there will be no match in 02312345.

Also, in case you want to precise to current century, or the 20th century, you may use /\b(?:19|20)\d{2}\b/ regex.

To extract the digits, use s[/\b\d{4}\b/].

'It was in 2015/16.'[/\b\d{4}\b/] # => 2015

See the Ruby demo