简体   繁体   中英

Writing a regex to validate username in Ruby

I'm stuck trying to figure out how to make this method work.

I want to return true if the username is made up of lowercase characters, numbers, and underscores, and is between 4 and 16 characters in length, otherwise return false.

def validate_usr(username)
  if username == /A[a-z0-9_]{4,16}Z/
    return true
  else return false
  end
end

I don't know what I'm doing wrong.

I'd use something like:

def validate_usr(username)
  !!username[/\A\w{4,16}\z/]
end

validate_usr('foo')                # => false
validate_usr('foobar')             # => true
validate_usr('FooBar')             # => true
validate_usr('Foo Bar')            # => false
validate_usr('12345678901234567')  # => false

\\w is the set [a-zA-Z0-9_] , which includes uppercase too. If you don't want upper-case then use [a-z0-9_] for the set.

[/\\A\\w{4,16}\\z/] is a String shortcut for applying a pattern to the string and returning the match. As the tests ran username[/\\A\\w{4,16}\\z/] returned:

username[/\A\w{4,16}\z/]  # => nil, "foobar", "FooBar", nil, nil

!! converts "truthy"/"falsey" to true / false , so here are the actual results:

!!username[/\A\w{4,16}\z/]  # => false, true, true, false, false

The end result is the method returns the desired true/false results only with less code.

I used \\z rather than \\Z because you're testing usernames, presumably for correctness prior to creating an account. \\z applies the test to the entire string, whereas \\Z will ignore a trailing line-end. If your code were to somehow allow a user to create a name with a trailing line-end \\Z would not give you an accurate validation result:

"foobar\n"[/\A\w{4,16}\Z/]  # => "foobar"
"foobar\n"[/\A\w{4,16}\z/]  # => nil

How about this?

def validate_usr(username)
  username =~ /\A[a-z0-9_]{4,16}\z/
end

Please read the following articles for the details of using regex.

I think you're pretty close you'll want to use =~ for the regex comparison. It will return 0 if it is valid.

The match operator =~ can be used to match a string against a regular expression. If the pattern is found in the string, =~ returns its starting position; otherwise, it returns nil

def validate_usr(username)
  (username =~ /\A[a-z0-9_]{4,16}\Z/) == 0
end

No regex:

def validate_usr(username)
  username.size.between?(4, 16) && username.count("^a-z0-9_").zero?
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM