1
if [[ $1  =~ ^\'*\"*[\d+\w+]+\'*\"*$ ]]
    then
        echo true
    else
        echo error
        exit 1
fi

This regex seems to be correct (verified with https://regexr.com, and other regex sites), however, the script will evaluate to false. Any idea why?

For this argument, I am expecting a line such as:

Will0w

To be matched, however, no luck.

Any help would be appreciated,

Thanks

2
  • 4
    "verified with regexr.com, and other regex sites": here is your error, bash regexes don't use the same syntax (and don't have the same behaviour) than javascript or php patterns. Search about the ERE (Extended Regular Expression) syntax. Commented Mar 4, 2018 at 19:50
  • 2
    Specifically, \d and \w are not supported. Commented Mar 4, 2018 at 20:08

2 Answers 2

2

Using :

if [[ $1  =~ ^\'*\"*[[:alnum:]]+\'*\"*$ ]]
    then
        echo true
    else
        echo error
        exit 1
fi
Sign up to request clarification or add additional context in comments.

1 Comment

[a-Z] depends on [a-z] and [A-Z] being adjacent in the current locale. Use the POSIX character class [[:alnum:]] instead, which also includes 0-9.
1

An alternative solution using grep:

if echo $1 | grep -qP "^\'*\"*[\d+\w+]+\'*\"*$"
    then
        echo true
    else
        echo error
        exit 1
fi

1 Comment

grep -qP "^\'*\"*[\d+\w+]+\'*\"*$" <<< "$1" will be more efficient as it eliminates the fork needed for the pipe.

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.