How to test that a string doesn't contain specific characters?

Hi ! :slight_smile:

I made this :

#!/bin/bash

rsa_dir="/etc/openvpn/easy-rsa/"
rsa_key_dir="/etc/openvpn/easy-rsa/keys/"
ccd_dir="/etc/openvpn/ccd/"
regex_special_char='[^a-zA-Z_0-9\s]'

cd $rsa_dir

while
read -p "Please can you enter the vpn's username : " username
[[ -z "$username" ]] || [[ ${#username} -lt 2 ]] || [[ ${#username} -gt 15 ]] || [[ "$username" =~ $regex_special_char ]]
do
echo "Your entry must not contain special characters and its length must do between 2-15 characters."
done

echo "ok"

I will wish to add a condition which test if there isn't these characters "� � � �" into the input. I think regex is a good way but my solution doesn't work.

Thanks by advance. :b::wink:

Hi,

Can you try like the following ( please note i removed capital letters to get different output ):

if [[ "avc123" =~ [a-z0-9���] ]]; then echo matches; else echo "does not match caps"; fi
matches
if [[ "ABC" =~ [a-z0-9���] ]]; then echo matches; else echo "does not match caps"; fi
does not match caps
if [[ "�xu�ti�" =~ [a-z0-9���] ]]; then echo matches; else echo "does not match caps"; fi
matches

I don't understand that you want me say:( because when I try [^a-zA-Z_0-9�����\s] it is not working.

Did you try the code shown in my previous post ( and adapt according to your need ) ?

What is not working ? Always write with details such as issued input, executed command and error message / output etc .

example :

# ./user_ovpn.sh
Please can you enter the vpn's username : usertest�
ok

And me I want the output says : "Your entry must not contain special characters and its length must do between 2-15 characters." on all the characters "�����", [^a-zA-Z_0-9\s] works fine with "&~"#'{(-` etc...) but not with accent

Hi,
Your regex in first post could work with correct locale, example:

$ XX="���"
$ LC_ALL=C
$ [[ "$XX" =~ [A-Za-z0-9_] ]] && echo ok
$ LC_ALL=fr_FR.UTF-8
$ [[ "$XX" =~ [A-Za-z0-9_] ]] && echo ok
ok

I choice "fr_FR.UTF-8" because I'm french :slight_smile:

Regards.

1 Like
# ./user_ovpn.sh
./user_ovpn.sh: line 9: warning: setlocale: LC_ALL: cannot change locale (fr_FR.UTF-8): No such file or directory

Me too, but it seems not worked

Hi,

For given input,

if [[ "usertest�" =~ [a-z0-9���] ]]; then echo "Entry should not contain special chars. Reenter correct entry" ; else echo "Does not contain special chars"; fi

Gives desired output:

In your case, you must set LC_ALL=C because you want exclude characters with accent.

Regards.

1 Like

Oh ok, I understand,merci, Thanks it works ! :):b:

see also

man ascii
man locale
man tr
# echo "0123456789a��e����i��u���A���E���I���U���" | tr -d [:alnum:]
�����������������������
# echo "0123456789a��e����i��u���A���E���I���U���" | tr -cd [:alnum:][:space:]
0123456789aeiuAEIU

Also read about character class

1 Like