Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Check if a string contain specific alphabets and comma

Tags:

string

bash

I am trying to parse and validate a string in Bash which is comma separated. The expected input is: X4,Y1,Z5

Conditions: The string should have only X,Y or Z alphabets, followed by any number. The string should not have any special characters other than comma. Please suggest.

X4,Y1,Z5 (This is OK)

Z2,y6,X1 (This is OK)

X3Y6,Z8 (This is not OK)

A1,B2,X8 (This is not OK)

N1P8* (This is not OK)

I have tried the following but this is not working as expected.

    if [[ ! $str =~ ['!@#$%^&*()_+'] ]] && [[ $str =~ [XYZxyz] ]]; then
            echo "OK"
    else
            echo "Not OK"
    fi 
like image 682
vashish Avatar asked Dec 07 '25 07:12

vashish


1 Answers

I suppose there are additional conditions of the problem that were implied but not emphasized, such as:

  1. The numbers may have more then one digit.
  2. Each of X,Y,Z letters should be used exactly once.

With that in mind, I think this code will do:

if [[ "$1" =~ ^[XxYyZz][0-9]+(,[XxYyZz][0-9]+){2}$ ]] && 
   [[ "$1" =~ .*[Xx].* ]] && 
   [[ "$1" =~ .*[Yy].* ]] && 
   [[ "$1" =~ .*[Zz].* ]] 
then
   echo OK
else
   echo Not OK
fi

Test cases:

#!/usr/bin/env bash

check() {
    [[ "$1" =~ ^[XxYyZz][0-9]+(,[XxYyZz][0-9]+){2}$ ]] && 
    [[ "$1" =~ .*[Xx].* ]] && 
    [[ "$1" =~ .*[Yy].* ]] && 
    [[ "$1" =~ .*[Zz].* ]]
}

test_check() {
    # code - expected exit code
    # value - string to test
    while read code value; do
        check "$value"
        if [[ $? == $code ]]; then
            echo -e "\e[1;32mPassed:\e[0m $value"
        else
            echo -e "\e[1;31mFailed:\e[0m $value"
        fi
    done
}

test_check <<EOF
0 x1,y2,z3
0 X1,Y2,Z3
1 x,y,z
1 1,2,3
1 1x,2y,3z
0 z1,x2,y3
1 a1,b2,c3
1 x1
1 x1,y2 z1
1 x1,x2
1 x1;y2;z3
1 x1,y2
1 x1,y2,y3
0 x100,Y500,z0
0 x011,y015,z0
1 x1,x2,y3,z4
1 x1,y1,z1 .
EOF

P.S.
If any of the X,Y,Z may appear in the string more than once or not appear at all, then [[ "$str" =~ ^[XxYyZz][0-9]+(,[XxYyZz][0-9]+)*$ ]] should work. I added here + for digits to appear one or more times after the letter, and quoted "$str" in case if there's a space in it (or, to be precise, any character from $IFS variable).

like image 69
Vitalizzare Avatar answered Dec 09 '25 00:12

Vitalizzare