2

I have used the example from http://www.regular-expressions.info/examples.html to validate the following code

while [[ ! $name =~ ^[a-Z][ \t][a-Z]. ]]; do

                echo "Please enter your Firstname and Surname e.g Joe Bloggs"                           # (a)Ask for NAME,TELEPHONE NUMBER,DOB #
                read name
                echo
        done

I am quite simply looking to ensure user enters first and second name with a space any help would be greatly appreciated!

1
  • @CodeGnome, no =~ is correct. Commented Jan 20, 2013 at 23:27

1 Answer 1

4

There are several problems with your regex:

  • You're checking for characters between a (lowercase) and Z (uppercase). This won't do what you expect, use [A-Za-z] to check both upper and lowercase letters.
  • You're missing repeat characters; use + to match one or more characters.
  • The end-of-match should be $, not . (which matches any single character).

Try this:

^[A-Za-z]+[\ \t][A-Za-z]+$

If you want to validate Uppercased first and last names you could use:

^[A-Z][a-z]+[\ \t][A-Z][a-z]+$

But this would not work with names like Marty McFly that don't follow that rule.

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

2 Comments

Sorry getting these errors: line 14: syntax error in conditional expression line 14: syntax error near \t][A-Za-z]+$' line 14: while [[ ! $name =~ ^[A-Za-z]+[ \t][A-Za-z]+$ ]]; do'
@Tricky Dicky, thanks, I forgot to add a backslash to escape the space in the regex, updated the answer.

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.