bash 如何检查字符串是否仅包含 AZ、az 和 0-9?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6257432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string only contains A-Z, a-z and 0-9?
提问by kheraud
What is the best way to validate a string with a pattern? I would use PCRE but I don't know if it is embedded in each shell and how to use it.
使用模式验证字符串的最佳方法是什么?我会使用 PCRE,但我不知道它是否嵌入在每个 shell 中以及如何使用它。
For example, how could I validate that variable only contains A-Z, a-Z and 0-9 and does not contain spaces, ', ", ... ?
例如,我如何验证该变量仅包含 AZ、aZ 和 0-9,并且不包含空格、'、"、...?
回答by Ignacio Vazquez-Abrams
$ [[ "foo" =~ ^[A-Za-z0-9]*$ ]] ; echo $?
0
$ [[ "foo " =~ ^[A-Za-z0-9]*$ ]] ; echo $?
1
回答by Martin
if [[ "$VARIABLE" =~ ^[[:alnum:]]*$ ]]; then do something; fi;
useful resources: http://bashshell.net/regular-expressions/, http://www.gnu.org/software/bash/manual/bashref.html
有用的资源:http://bashshell.net/regular-expressions/,http://www.gnu.org/software/bash/manual/bashref.html
回答by Seth Robertson
if `echo $VARIABLE | egrep '[^A-Za-z0-9]'`; then echo VARIABLE IS BAD; fi
A pure shell option
纯 shell 选项
case "$VARAIBLE" in *[^A-Za-z0-9]*) echo VARIABLE IS BAD;; esac
回答by Jo So
The one and only portable (no bash crap) way:
唯一的便携(没有 bash 废话)方式:
`[ "${var%%*[^A-Za-z0-9]*}" ]`
Note that no external program is started, so this is more performant than grepet al. solutions.
请注意,没有启动任何外部程序,因此这比grep等人的性能更高。解决方案。
Note that character classes are generally (not only in shell) locale-sensitive.
请注意,字符类通常(不仅在 shell 中)对区域设置敏感。
var=?
[ "${var%%*[^a-z]*}" ] && echo match # prints "match"
So you might want to consider temporarily setting the locale to Cor make the class yourself
因此,您可能需要考虑暂时将语言环境设置为C或自己创建类
`[ "${var%%*[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*}" ]`

