我试图用正则表达式添加名称检查,它只传递字符和数字,但不传递输出中的特殊符号。我写了这段代码,但它不起作用。当我只键入带有数字或chars+special符号的字符时,它也会显示“不确定”
#!/bin/bash
regex="/^[a-zA-Z0-9_]+$/gm"
read -p "Type smth: " text
if [[ $text =~ $regex ]]
then
echo "ok"
else
echo "not ok"
fi这是输出:
user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello$#!
not ok
user@localhost:~/Documents/scripts$ ./testregex.sh
Type smth: hello
not ok发布于 2022-07-06 10:16:27
您可以使用
if [[ $text =~ ^[[:alnum:]_]+$ ]]
then
echo "ok"
else
echo "not ok"
fi详细信息
^ -字符串的开始[[:alnum:]_]+ -一个或多个字母、数字或下划线$ -字符串的末端。注意没有正则分隔符字符。
见在线演示。
https://stackoverflow.com/questions/72881712
复制相似问题