Bash shell if 语句匹配正则表达式和花括号 {}

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

Bash shell if statement matching regex with curly braces {}

regexbashif-statementcurly-braces

提问by Colin

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.

我一直在编写一个小 bash 脚本来帮助经验不足的 Linux 用户使用一些命令。一件事似乎在逃避我,那就是在为 if 语句进行模式匹配时使用花括号。

regex="[A-Za-z0-9]/{5/}"
if [[  =~ $regex ]]
then
  num=
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?

这应该捕获正好是 5 个字符的任何 AZ、az 或 0-9,不是吗?

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

回答by Nico Rodsevich

Maybe the problem is here:

也许问题出在这里:

regex="[A-Za-z0-9]/{5/}"

Should be:

应该:

regex="[A-Za-z0-9]\{5\}"

(watch backslashes)

(注意反斜杠)

回答by murgatroid99

You should try

你应该试试

regex="[A-Za-z0-9]{5}"

Edit:Another change you could try is

编辑:您可以尝试的另一个更改是

if [[ "" =~ $regex ]]

Edit2:If you just want to determine if $2is 5 characters long, you could try something like

Edit2:如果您只想确定是否$2为 5 个字符长,您可以尝试类似

if [ ${#2} = 5]

回答by glenn Hymanman

Hmm, works for me in bash version "GNU bash, version 4.1.10(4)-release"

嗯,在 bash 版本“GNU bash,版本 4.1.10(4)-release”中对我有用

$ regexp="[[:alnum:]]{5}"
$ set -- "" abcde
$ [[ "" =~ $regexp ]] && echo y || echo n
y
$ set -- "" foo
$ [[ "" =~ $regexp ]] && echo y || echo n
n

Note that the right-hand side must notbe quoted:

请注意,右侧不得引用:

$ set -- "" abcde
$ [[ "" =~ "$regexp" ]] && echo y || echo n
n

You don't actually need a regular expression for this:

您实际上不需要为此使用正则表达式:

$ glob="[[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]][[:alnum:]]"
$ set -- "" abcde
$ [[ "" == $glob ]] && echo y || echo n
y
$ set -- "" foo
$ [[ "" == $glob ]] && echo y || echo n
n