How to check if string contains characters in regex pattern in shell?

19,554

Solution 1

One way of doing it is using the grep command, like this:

 grep -qv "[^0-9a-z-]" <<< $STRING

Then you ask for the grep returned value with the following:

if [ ! $? -eq 0 ]; then
    echo "Wrong string"
    exit 1
fi

As @mpapis pointed out, you can simplify the above expression it to:

grep -qv "[^0-9a-z-]" <<< $STRING || exit 1

Also you can use the bash =~ operator, like this:

if [[ ! "$STRING" =~ [^0-9a-z-] ]] ; then  
    echo "Valid"; 
else 
    echo "Not valid"; 
fi

Solution 2

case has support for matching:

case "$string" in
  (+(-[[:alnum:]-])) true ;;
  (*) exit 1 ;;
esac

the format is not pure regexp, but it works faster then separate process with grep - which is important if you would have multiple checks.

Share:
19,554
Justin
Author by

Justin

Updated on June 04, 2022

Comments

  • Justin
    Justin about 2 years

    How do I check if a variable contains characters (regex) other than 0-9a-z and - in pure bash?

    I need a conditional check. If the string contains characters other than the accepted characters above simply exit 1.

  • mpapis
    mpapis over 10 years
    you can also grep ... || exit 1
  • Justin
    Justin over 10 years
    Do I need to escape the - in [^0-9a-z-], so [^0-9a-z\-]? Also, isn't the first case echo "Not valid" instead of echo "Valid".
  • higuaro
    higuaro over 10 years
    No, you don't need to escape the - (not even in the grep solution), the first case should be Valid because the conditional is negated (using the ! operator before the regex test), the condition ask if $STRING contains a character that is not a digit, - or a letter, if this evaluates to false ($STRING contains only letters, digits and/or -) the negation turns the evaluation true