Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash need to test for alphanumeric string

Trying to verify that a string has only lowercase, uppercase, or numbers in it.

if ! [[ "$TITLE" =~ ^[a-zA-Z0-9]+$ ]]; then echo "INVALID"; fi

Thoughts?

* UPDATE *

The variable TITLE currently only has upper case text so it should pass and nothing should be outputted. If however I add a special character to TITLE, the IF statement should catch it and echo INVALID. Currently it does not work. It always echos invalid. I think this is because my regex statement is wrong. I think the way I have it written, its looking for a title that has all three in it.

Bash 4.2.25

The idea is, the user should be able to add any title as long as it only contains uppercase, lowercase or numbers. All other characters should fail.

* UPDATE *

If TITLE = ThisIsAValidTitle it echos invalid.

If TITLE = ThisIs@@@@@@@InvalidTitle it also echos invalid.

* SOLUTION *

Weird, well it started working when I simplified it down to this:

TEST="Valid0"
if ! [[ "$TEST" =~ [^a-zA-Z0-9] ]]; then
  echo "VALID"
else
  echo "INVALID"
fi

* REAL SOLUTION *

My variable had spaces in it... DUH

Sorry for the trouble guys...

* FINAL SOLUTION *

This accounts for spaces in titles

if ! [[ "$TITLE" =~ [^a-zA-Z0-9\ ] ]]; then
  echo "VALID"
else
  echo "INVALID"
fi
like image 682
Atomiklan Avatar asked Aug 04 '13 10:08

Atomiklan


People also ask

How do you check if a string is alphanumeric or not?

Python String isalnum() Method The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space)!

How do you check if a string starts with a character in bash?

Introduction – In bash, we can check if a string begins with some value using regex comparison operator =~ .

What =~ in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.


1 Answers

I'd invert the logic. Test for invalid characters and echo a warning if at least one is present:

if [[ "$TITLE" =~ [^a-zA-Z0-9] ]]; then
  echo "INVALID"
fi

With that said, your original check worked for me, so you probably need to provide more context (i.e. a larger portion of your script).

like image 193
Ansgar Wiechers Avatar answered Sep 19 '22 23:09

Ansgar Wiechers