3

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

5
  • Good Q except you should include sample input (both good and bad). Good luck. Commented Oct 30, 2016 at 16:45
  • What do you actually want to check with your reg ex?Give some examples Commented Oct 30, 2016 at 16:47
  • 3
    None of this is regex. It's a different kind of pattern called globs. They can look similar, but they're not the same. Commented Oct 30, 2016 at 16:49
  • I managed to emit my regex example. Oops. [[ $string =~ ^[a-zA-Z0-9]{5}*$ ]] didn't work when I reversed the logic. Commented Oct 30, 2016 at 17:01
  • 1
    @joemobaggins [[ $string =~ ^[a-zA-Z0-9]{5}$ ]] Commented Oct 30, 2016 at 17:04

1 Answer 1

3

I suggest to replace

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

by

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

to match a regex.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey, thanks allot, that works. When I tried [[ $string =~ ^[a-zA-Z0-9]{5}*$ ]] and reversed the logic, It didn't work. Why so?
This works for me with bash version 4: string="a1B2c"; [[ $string =~ ^[a-zA-Z0-9]{5}*$ ]] && echo match
could you explain the && syntax to me? I realise it's an AND. But I don't understand it in this context.
Yes, && is a boolean AND. If [[ ... ]] is true execute echo match. Long version with an else branch: string=a1B2c; if [[ $string =~ ^[a-zA-Z0-9]{5}*$ ]]; then echo match; else echo "no match"; fi

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.