gpt4 book ai didi

regex - bash 扩展的正则表达式运算符

转载 作者:行者123 更新时间:2023-12-03 23:56:13 25 4
gpt4 key购买 nike

我正在尝试使用 bash 中可用的扩展正则表达式运算符(?、*、+、@、!)。手册说我只需要用括号括起来一个模式列表,然后在左括号之前使用运算符。所以如果我想要一个零个或多个 a 的模式:

if [[ "$1" =~ *(a) ]]
then
echo $1
fi

但这不起作用。我做错了什么?

最佳答案

man bash:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

我在这里引用了整件事,因为我认为了解它很有用。您在右侧使用标准 POSIX 扩展正则表达式。

特别是,右侧的表达式可能匹配左侧操作数的子字符串。因此,要匹配整个字符串,请使用 ^$ anchor :

if [[ "$1" =~ ^a*$ ]]
then
echo $1
fi

关于regex - bash 扩展的正则表达式运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12614267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com