0

I'm trying to add name-checking with regular expression, that passes only characters and digits but no special symbols given from the output. I wrote this code, but it's does not working. It shows "not ok" either when I'm typing only characters with digits or chars+special symbols

#!/bin/bash
regex="/^[a-zA-Z0-9_]+$/gm"
read -p "Type smth: " text

if [[ $text =~ $regex ]]
then
    echo "ok"
else
    echo "not ok"
fi

Here's the output:

user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello$#!
not ok

user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello
not ok
2
  • 4
    Remove surrounding slashes and the gm option from your regex as regex="^[a-zA-Z0-9_]+$". Commented Jul 6, 2022 at 10:59
  • 1
    Your regex is actually Perl-style matching operator, not just a regular expression. Commented Jul 6, 2022 at 22:15

1 Answer 1

2

You can use

if [[ $text =~ ^[[:alnum:]_]+$ ]]
then
    echo "ok"
else
    echo "not ok"
fi

Details:

  • ^ - start of string
  • [[:alnum:]_]+ - one or more letters, digits or underscores
  • $ - end of string.

Note the absence of regex delimiter chars.

See the online demo.

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

Comments

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.