2

I was giving this regex /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,}\z/ and I'm to use it in order to verify the validity of an email address.

This is my first Ruby code and I'm not sure how to do it. I was told to use the .match method, which returns MatchData object. But how do I go on verifying that the MatchData object confirms the validity?

I attempted using the following, but it seems that it's accepting any string, even not an email address.

#Register new handler
def register_handler

    email_regex = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,}\z/
    email = "invalid"
    unless email =~ email_regex then
        puts("Insert your e-mail address:")
        email = gets
    end

    puts("email received")


end

What is the correct way to do this? Either using .match or the method I attempted above.

2 Answers 2

3

The regex matches email addresses:

'invalid' =~ email_regex
=> nil # which boolean value is false

'[email protected]' =~ email_regex
=> 0 # which boolean value is true

however:

"[email protected]\n" =~ email_regex
=> nil

The newline character \n is appended by gets to every input.

That is why, the until loop will run forever regardless of what you will type in the terminal. The matching result will always be nil because of the newline character.

Try using gets.chomp, which will trim the newline character and your code should work.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Edited the regex and put () to capture group and the beginning and the end

re = /^([\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,})$/m
str = '[email protected]
[email protected]
[email protected]
....
a@bdotcom


aasdf.com

www.yahoo.com'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Running sample code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.