Bash shell if 语句匹配带有大括号 {} 的正则表达式
我一直在编写一些 bash 脚本来帮助经验不足的 Linux 用户使用一些命令。我似乎没有注意到一件事,那就是在对 if 语句进行模式匹配时使用花括号。
regex="[A-Za-z0-9]/{5/}"
if [[ $2 =~ $regex ]]
then
num=$2
else
echo "Invalid entry"
exit 1
fi
这应该捕获任何恰好 5 个字符的 AZ、az 或 0-9,不是吗?
我已经尝试了很多次,很多变体,很多引用,有或没有转义...似乎没有任何效果:
+ regex='[A-Fa-f0-9]/{5/}'
+ [[ abcd1 =~ [A-Za-z0-9]/{5/} ]]
+ echo 'Invalid entry'
我缺少什么想法吗?
GNU bash, version 3.2.39(1)-release
I've been writing a little bash script to aid less experienced Linux users with some commands. One thing seems to be escaping me and that's using curly braces when doing pattern matching for an if statement.
regex="[A-Za-z0-9]/{5/}"
if [[ $2 =~ $regex ]]
then
num=$2
else
echo "Invalid entry"
exit 1
fi
This should capture anything A-Z, a-z or 0-9 that is exactly 5 characters, should it not?
I've tried many times, many variations, many quotes, with and without escaping... Nothing seems to be working:
+ regex='[A-Fa-f0-9]/{5/}'
+ [[ abcd1 =~ [A-Za-z0-9]/{5/} ]]
+ echo 'Invalid entry'
Any ideas what I'm missing?
GNU bash, version 3.2.39(1)-release
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许问题就在这里:
应该是:(
注意反斜杠)
Maybe the problem is here:
Should be:
(watch backslashes)
您应该尝试
Edit: 您可以尝试的另一个更改是
Edit2: 如果您只想确定
$2
是否为 5 个字符长,您可以尝试类似的东西You should try
Edit: Another change you could try is
Edit2: If you just want to determine if
$2
is 5 characters long, you could try something like嗯,在 bash 版本“GNU bash,版本 4.1.10(4)-release”中为我工作
,请注意,右侧不得被引用:
您实际上不需要正则表达式为了这:
Hmm, works for me in bash version "GNU bash, version 4.1.10(4)-release"
Note that the right-hand side must not be quoted:
You don't actually need a regular expression for this: