4

I can't get a string with spaces to validate. It works without spaces, but when I include a space in the string it fails. I have googled furiously but can't get it to work.

if [[ $string =~ ^"[A-Za-z ]"$ ]]; then
    # true
else 
    # false
fi

I'm not sure what I'm missing here...

1
  • Have a look at this demo. You need '^[A-Za-z ]*$' to match a string that can contain 0 or more letters or spaces. Commented Feb 19, 2016 at 8:58

2 Answers 2

6

Use a variable to store your regex:

re='^[A-Za-z ]+$'

Then use it as:

[[ "string" =~ $re ]] && echo "matched" || echo "nope"
matched

[[ "string with spaces" =~ $re ]] && echo "matched" || echo "nope"
matched

If you want inline regex then use:

[[ "string with spaces" =~ ^[A-Za-z\ ]+$ ]] && echo "matched" || echo "nope"
matched

Or else use [[:blank:]] property:

[[ "string with spaces" =~ ^[A-Za-z[:blank:]]+$ ]] && echo "matched" || echo "nope"
matched
Sign up to request clarification or add additional context in comments.

Comments

-3

I should instead use following regex if its always space instead..

if [[ $string =~ ^"[A-Za-z ](\s)"$ ]]; then
    # true
else 
    # false
fi

Cheers :)

1 Comment

Those quotes are wrong and even if they weren't there, this pattern wouldn't permit a string with any number of characters other than 2.

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.