开发者

How to check if a string only contains A-Z, a-z and 0-9?

What is the best way to validate a string with a pa开发者_运维技巧ttern? I would use PCRE but I don't know if it is embedded in each shell and how to use it.

For example, how could I validate that variable only contains A-Z, a-Z and 0-9 and does not contain spaces, ', ", ... ?


$ [[ "foo" =~ ^[A-Za-z0-9]*$ ]] ; echo $?
0
$ [[ "foo " =~ ^[A-Za-z0-9]*$ ]] ; echo $?
1


if `echo $VARIABLE | egrep '[^A-Za-z0-9]'`; then echo VARIABLE IS BAD; fi

A pure shell option

case "$VARAIBLE" in *[^A-Za-z0-9]*) echo VARIABLE IS BAD;; esac


if [[ "$VARIABLE" =~ ^[[:alnum:]]*$ ]]; then do something; fi;

useful resources: http://bashshell.net/regular-expressions/ , http://www.gnu.org/software/bash/manual/bashref.html


The one and only portable (no bash crap) way:

`[ "${var%%*[^A-Za-z0-9]*}" ]`

Note that no external program is started, so this is more performant than grep et al. solutions.

Note that character classes are generally (not only in shell) locale-sensitive.

var=ä
[ "${var%%*[^a-z]*}" ] && echo match  # prints "match"

So you might want to consider temporarily setting the locale to C or make the class yourself

`[ "${var%%*[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*}" ]`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜