Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex comparison issue

Tags:

regex

bash

I have the following function

checkFormat()
{
        local funcUserName=$1
        if [[ "$funcUserName" != [a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9] ]];then
                echo "1"
        else
                echo "0"
        fi
}

if [[ $string != [a-zA-Z0-9]* ]]

Only returns true if the first character is not [a-zA-Z0-9] if [[ $string != [a-zA-Z0-9]{5} ]]

Never returns true.

if [[ $string != [a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9] ]]

Returns as I want it to. Why is this?

The code is to check that a username is 5 characters long and alphanumeric i.e. Joe12 or 12345 but not %$134.

bash version 4.2.37

like image 730
joemobaggins Avatar asked Apr 29 '26 07:04

joemobaggins


1 Answers

I suggest to replace

if [[ $string != [a-zA-Z0-9]{5} ]]

by

if [[ ! $string =~ ^[a-zA-Z0-9]{5}*$ ]]

to match a regex.

like image 196
Cyrus Avatar answered May 02 '26 10:05

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!