Neil
Neil

Reputation: 141

ruby regex to check for a valid sentence

I'm creating a basic sentence checker that takes a string and determines whether it is valid or not using the following rules

  1. The sentence must start with a valid capital letter followed by a lowercase letter
  2. All other characters must be lowercase letters
  3. There must be a single space between each word
  4. The sentence must end with a terminal mark . or ? or !

I've tried the following code - which covers 1 , 4. But 2 works only after the first character

puts "Enter your sentence: " 
sentence = gets.chomp

    if (sentence =~ /^[A-Z][a-z0-9_.]\s/ && sentence.end_with?('.','?','!')) 
        puts "Correct >>> " + sentence + " <<< Is a valid sentence!"
    else 
        puts "Incorrect >>>  " + sentence + " Is NOT a valid sentence "
    end

Expected result

Enter your sentence: Hello! Correct >>> Hello! <<< Is a valid sentence!

Enter your sentence: hello! Incorrect >>> hello! Is NOT a valid sentence

Enter your sentence: HHello! Incorrect >>> HHello! Is NOT a valid sentence

Unexpected result HeLlo! Correct >>> HeLlo! <<< Is a valid sentence!

For single space between each word using \s but it allows more than one space

Upvotes: 0

Views: 375

Answers (1)

Jay Dorsey
Jay Dorsey

Reputation: 3662

Your regex is only checking for a capital letter, followed immediately by lowercase letter/number/underscore/any character, followed by a space.

You need something that allows for multiple values after the first that meet your criteria. You can use a + for this

Here's a sample that meets your test criteria. It doesn't meet your full set of rules, however.

def sentence?(sentence)
  sentence = sentence.strip

  if sentence =~ /^[A-Z][a-z0-9_. ]+[\.?!]$/
    puts "  Correct >>> " + sentence + " <<< Is a valid sentence!"
  else
    puts "INCORRECT >>> " + sentence + " Is NOT a valid sentence "
  end
end

sentence?('Hello!') # valid
sentence?('hello!') # not valid
sentence?('HHello!') # not valid
sentence?('HeLlo!') # not valid

You can use rubular to see how the regex captures various sentences/phrases

Here's something that meets the criteria you described

def real_sentence?(sentence)
  sentence = sentence.strip

  if sentence =~ /^[A-Z][a-z]+(\s[a-z]+){0,}[?!\.]$/
    puts "  Correct >>> " + sentence + " <<< Is a valid sentence!"
  else
    puts "INCORRECT >>> " + sentence + " Is NOT a valid sentence "
  end
end

real_sentence?('Hello how are you John?!') # not valid
real_sentence?('hello how are you?') # not valid
real_sentence?('Hello!') # valid
real_sentence?('Hello how are you?') # valid

Upvotes: -1

Related Questions