开发者

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

开发者 https://www.devze.com 2023-03-11 21:27 出处:网络
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.

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

精彩评论

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