Home > Back-end >  Regex Ruby Confusion
Regex Ruby Confusion

Time:10-12

I'm currently building an arbitrary ruby program but my name validation through ruby (not using rails yet) to validate is consistently not working because when I enter pure numbers it runs fine when it shouldn't.

def user_input
  puts 'What is your name?'
  user_name = gets.chomp
  name_pattern = Regexp.new('/\A[^0-9`!@#\$%\^&* _=] \z/')
  while user_name =~ name_pattern
    puts 'please enter a real name'
    user_name = gets.chomp
  end
  user_name
end

def main
  user_name = user_input
  puts "\n"
  puts user_name.to_s
end

In addition I've tried the regex /[a-z] / just to check if it is my regex and it appears that is not as well since when I type 33 with regex /[a-z] / it also works just fine? What am I doing wrong here lol.

CodePudding user response:

The problem is that your regex contains a forward slash at the beginning and end.

This code defines a regex for "one or more lower-case letters":

name_pattern = /[a-z] /
# OR
name_pattern = Regex.new('[a-z] ')

This code defines a regex for "the whole string can only consist of one-or-more lower-case characters":

name_pattern = /\A[a-z] \z/
# OR
name_pattern = Regex.new('\A[a-z] \z')

This code defines a regex for "the whole string can only consist of characters that are not digits, nor certain symbols":

name_pattern = /\A[^0-9`!@#\$%\^&* _=]\z/
# OR
name_pattern = Regex.new('\A[^0-9`!@#\$%\^&* _=]\z')

Your code is confusing the two syntaxes, by adding literal slashes to the start and end of the regex.

CodePudding user response:

You are requiring a / before start of string (\A), so your /\A[^0-9`!@#\$%\^&* _=] \z/ pattern is a pattern that never matches any string.

Use

name_pattern = /\A[^0-9`!@#$%^&* _=] \z/

Or, if you prefer a Regexp.new notation,

name_pattern = Regexp.new('\A[^0-9`!@#$%^&* _=] \z')

Also, $ inside a character class never requires escaping, [$] always matches a literal $ char.

The ^ char inside a character class only needs escaping if it is the first char in the class. Here, it is not the first, so there is no need escaping it.

  • Related