gpt4 book ai didi

linux - BASH =~ 包含子串 : "+" or a regex character behavior

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:06 25 4
gpt4 key购买 nike

想知道为什么以下内容对角色不起作用:+

字符 "\""(""*" 是有意义的,即 * 将扩展为当前目录中的文件夹/文件(在命令行 shell 扩展期间)以及类似的 \( 将期望结束字符起作用,但我的理解是 "+" 应该像 "-" 那样工作。

PS:我知道在 IF 语句中放置双引号,即“${o}”,将适用于我下面的测试用例中的所有字符。在带或不带双引号的 IF 语句中使用\${o} 将导致所有检查失败。

$ for o in - + \` ~ \~ , _ = / \\ ! @ \# $ \$ % ^ \& \* \( \); do a="a${o}b${o}c";if [[ $a =~ ${o} ]]; then echo "${o} exists in $a and =~ works"; else echo -e "\ncharacter ${o} doesn't work with =~\n"; fi; done
- exists in a-b-c and =~ works

character + doesn't work with =~

` exists in a`b`c and =~ works
/home/ubuntu exists in a/home/ubuntub/home/ubuntuc and =~ works
~ exists in a~b~c and =~ works
, exists in a,b,c and =~ works
_ exists in a_b_c and =~ works
= exists in a=b=c and =~ works
/ exists in a/b/c and =~ works

character \ doesn't work with =~

! exists in a!b!c and =~ works
@ exists in a@b@c and =~ works
# exists in a#b#c and =~ works
$ exists in a$b$c and =~ works
$ exists in a$b$c and =~ works
% exists in a%b%c and =~ works
^ exists in a^b^c and =~ works
& exists in a&b&c and =~ works

character * doesn't work with =~


character ( doesn't work with =~

) exists in a)b)c and =~ works

最佳答案

这个问题背后的根本误解是 =~ 是一个子字符串搜索运算符。 不是

=~ 的右侧被评估为 POSIX ERE 表达式。 =~ 因此是一个正则表达式匹配运算符,当右侧被引用以使其内容成为文字时(或者当已知该字符串仅匹配自身时,它恰好经常用于搜索解释为 ERE)。


+ 在正则表达式中表示“1 个或多个前面的标记”——正如 * 表示“0 个或多个前面的标记” ".

因此,[[ $foo =~ + ]][[ $foo =~ * ]] 都没有意义,因为它们正在检查零或-多个根本不存在的前置标记

类似地,() 在 ERE 中作为匹配组的开始和结束具有意义,因此当它们被给出时(未转义/未引用),它们导致无效的正则表达式。

如果您引用扩展,相比之下,包含的所有字符都将被视为文字,而不是被视为正则表达式元字符,从而导致预期的行为。


如果你想检查一个文字字符是否包含在一个字符串中,要么引用它 -- [[ $foo =~ "$o"]] -- 或者使用 glob-style模式:[[ $foo = *"$o"* ]]

关于linux - BASH =~ 包含子串 : "+" or a regex character behavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40748821/

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