Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow spaces in string - bash

Tags:

regex

bash

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...

like image 721
ryansin Avatar asked Oct 20 '25 13:10

ryansin


1 Answers

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
like image 160
anubhava Avatar answered Oct 22 '25 09:10

anubhava