Tintin81
Tintin81

Reputation: 10207

How to match a string with a pattern and extract a value from it?

In my Rails app I am looking for a way to return certain parts of a string using a pattern.

get_value(string: "21-05-2017-01", pattern: "DD-MM-YYYY-NN", substring: "NN") # => "01"

get_value(string: "21-05-2017-01", pattern: "DD-MM-YYYY-NN", substring: "MM") # => "05"

Where the number and position of Ns in the pattern may vary.

How can this be done?

Thanks for any help.

Upvotes: 0

Views: 122

Answers (4)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

One more solution:)

def get_value(string:, pattern:, substring:)
  pattern_select = pattern.split('-').zip(string.split('-')).to_h # => {"DD"=>"21", "MM"=>"05", "YYYY"=>"2017", "NN"=>"01"}
  pattern_select.fetch(substring, "Undefined substring: #{substring}")
end

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36860

To get position of "NN" ins "DD-MM-YYYY-NN" it would be

my_index = "DD-MM-YYYY-NN".index("NN")

Once you have the index, you can extract the index (for appropriate length) from the string...

result = "21-05-2017-01"[my_index, "NN".size]
=> "01"

Putting it all together (and handling the case of no match for substring)...

def get_value(options)
  return nil if (my_index = options[:pattern].index[options[:substring]) == nil
  string[my_index, options[:substring].size)
end

Upvotes: 1

Ursus
Ursus

Reputation: 30056

This can be as complex as you want probably. But a simple implementation could be.

def get_value(string, pattern, substring)
  index = pattern.index(substring)
  raise ArgumentError unless index
  string[index, substring.size]
end

get_value("21-05-2017-01", "DD-MM-YYYY-NN", "NN")
 => "01"

Upvotes: 3

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

Try this:

def get_value(hash = {})
  hash[:pattern].split('-').zip(hash[:string].split('-')).map { |k,v| v if k == hash[:substring] }.compact.first
end

You can call it as

get_value({string: "21-05-2017-01", pattern: "DD-MM-YYYY-NN", substring: "NN"})
# => "01"

Upvotes: 1

Related Questions