检查字符串是否仅包含指定的字符(包括下划线) [英] Check if a string contains only specified characters including underscores

查看:46
本文介绍了检查字符串是否仅包含指定的字符(包括下划线)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里收到一个字符串(一个单词),其条件如下:字符串只能包含字母字符(aA-zZ)和下划线.不允许输入数字和其他字符.

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.

我该如何在BASH中做到这一点?

How may I do this in BASH?

推荐答案

使用 =〜根据(POSIX扩展的)正则表达式检查字符串.有关更多信息,请参见手册页 bash(1) regex(7).

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

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

这篇关于检查字符串是否仅包含指定的字符(包括下划线)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆