Change the regular expression to check that the password has at least one uppercase letter. Ruby

I have this regex

/^[A-Za-z0-9_-]{6,30}$/

      

I want to change it to check that the password has at least one uppercase letter

I tried putting + sign after AZ + but it didn't work

 /^[A-Z+a-z0-9_-]{6,30}$/

      

Can you help me?

+3


source to share


2 answers


You can use:

/^(?=.*?[A-Z])[\w-]{6,30}$/

      



Here (?=.*?[A-Z])

is a positive lookahead that makes sure your regex has at least one uppercase English letter. Also note which is the \w

same as [a-zA-Z0-9_]

.

0


source


Sorry, but I'm really bad at looking at regex, but I would like to suggest another solution, which is a one-liner :

# Data:
passwords = %w(
  tlkjadfjklk
  asdfkjlaj3223$%^&*
  kljjkl32jklfa%^
  ABCDLK233223
  Aiou34i^&*
  23fsaAiou34i^&*
  kljasf90843klj3()*Dlkjafa323
  klAjasf90843klj3()*Dlkjafa323
  A
  ABCDEF
  klAjasf90843klj3klAjasf90843klj3klAjasf90843klj3)

# Code:
passwords.each{|pwd| p [/^(.*?[A-Z]+)/, /[A-Z]+(.*?)$/].inject(0){|sum, regex| sum += regex.match(pwd) ? $~[1].size : 0}.between?(6, 30)}

# Results:
false
false
false
true
true
true
true
true
false
true
false

      



To make it a little clearer, below is an extended version of the one-liner:

regex_begin = /^(.*?[A-Z]+)/
regex_after = /[A-Z]+(.*?)$/
passwords.each do |pwd|
  len = [regex_begin, regex_after].inject(0) do |sum, regex|
    sum += regex.match(pwd) ? $~[1].size : 0
  end
  p len.between?(6, 30)
end

      

0


source







All Articles