bash 检查字符串是否只包含指定的字符,包括下划线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20763980/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:05:11  来源:igfitidea点击:

Check if a string contains only specified characters including underscores

stringbashcharacter

提问by Khaleal

I want to receive a string (one word) from the user, with the following criteria: The string may contain only alphabetical characters (aA-zZ) and underscores. Digits and other characters are not allowed.

我想从用户那里接收一个字符串(一个单词),符合以下条件:该字符串可能只包含字母字符 (aA-zZ) 和下划线。不允许使用数字和其他字符。

How may I do this in BASH?

我怎么能在 BASH 中做到这一点?

回答by lilydjwg

Use =~to check a string against a (POSIX extended) regex. See manpages bash(1)and regex(7)for more.

用于=~根据(POSIX 扩展)正则表达式检查字符串。请参阅联机帮助页bash(1)regex(7)更多信息。

# assume your string is in variable $s
if [[ $s =~ ^[A-Za-z_]+$ ]]; then
  # it matches
else
  # doesn't match
fi