Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex does not accept slash

Tags:

regex

linux

bash

i am pretty new to bash shell scripting (and linux too)... i try to do a simple script which involves some regex for a string given by keyboard from a user.

            clear
            read -p "Insert e-mail > "
            if [[ $REPLY =~ ^[.] ]]
            then
                    echo "ERROR (code 1): e-mail cannot start with \".\""
            elif [[ $REPLY =~ .[.]$ ]]
            then
                    echo "ERROR (code 2): e-mail cannot end with \".\""
            else
                    if [[ $REPLY =~ ^[0-9][0-9a-zA-Z!#$%^\&\'*+-]+$ ]] #THIS IS WHERE I NEED HELP
                    then
                            echo "Good!"
                    else
                            echo "Bad!"
                    fi
            fi

so what i want to do is to make a regex
so that the user cant start with . or end with . (i pretty much did that and its working)...
next what i wanted to do was make the string start with a number and i did that with ^[0-9] (i think this is correct)
and after that..string could be anything like a number 0-9 or letters a-z and A-Z or the next characters: !#$%^&'*+-/
so when user entered 1& (it starts with number and the rest is in the acceptable characters) but it didn't work.. because it need to be \& (at the regex formula).
next the same problem occurred to character ' what i did, was to add again a backslash to regex formula (\') and it worked..
then i tried to do the same with / character (slash character) so what i did was add a backslash / (backslash slash) but when user entered 1/ (it starts with number and the rest are acceptable characters) unfortunately it printed "Bad!" ... it should print Good!..
why is that happening?
i tried \/ and \\/ but still... cant understand why it doesn't work!

like image 986
Sotnam96 Avatar asked Oct 16 '25 16:10

Sotnam96


2 Answers

Problem is presence of ! in your character class that is doing history expansion.

I suggest declaring your regex beforehand like this:

re="^[0-9][0-9a-zA-Z\!#$%^&/*'+-]+$"

Then use it as:

s='1/'
[[ $s =~ $re ]] && echo "good" || echo "bad"
good
like image 196
anubhava Avatar answered Oct 18 '25 08:10

anubhava


Actually, /s work in character classes just fine:

$ [[ "1/" =~ ^[0-9][/]+$ ]]; echo $?
0
like image 44
Charles Duffy Avatar answered Oct 18 '25 07:10

Charles Duffy



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!