user1993565 user1993565 - 2 months ago 15
Ruby Question

Check 4 chars with regex Ruby console input

I have 4 chars, first one is letter 'L' for example, the other two are numbers and the last one is letter again, all of them are separated by one space. User is entering them in the Ruby console. I need to check that they are separated by one space and don't have other weird characters and that there is nothing after the last letter.

So if a user enters for example gets.chomp = 'L 5 7 A', I need to check that everything is ok and separated by only one space and return input[1], input[2], input[3]. How can I do that? Thanks.

Answer

You can do something like this:

puts "Enter string"
input = gets.chomp
r = /^(L)\s(\d)\s(\d)\s([A-Z])$/                                        
matches = input.match r

puts matches ? "inputs: #{$1}, #{$2}, #{$3}, #{$4}" : "input-format incorrect"

Here $1 is the first capture, similarly for $2, $3 etc. If you want to store the result in an array you can use:

matches = input.match(r).to_a

then the first element is the entire match, followed by each capture.

Comments