与通配符匹配的正则表达式

标签 regex bash glob

我正在尝试检查给定字符串中是否包含 .rel6. 。我对 Bash 正则表达式的行为有点困惑。我在这里缺少什么?

os=$(uname -r)                        # set to string "2.6.32-504.23.4.el6.x86_64"

[[ $os =~ *el6*    ]] && echo yes     # doesn't match, I understand it is Bash is treating it as a glob expression
[[ $os =~ el6      ]] && echo yes     # matches
[[ $os =~ .el6     ]] && echo yes     # matches
[[ $os =~ .el6.    ]] && echo yes     # matches
[[ $os =~ ".el6."  ]] && echo yes     # matches
[[ $os =~ *".el6." ]] && echo yes     # * does not match - why? *
[[ $os =~ ".el6."* ]] && echo yes     # matches

re='\.el6\.'
[[ $os =~ $re      ]] && echo yes     # matches

特别是这个:

[[ $os =~ *".el6." ]] && echo yes

最佳答案

=~ 运算符对其左侧的字符串和右侧的表达式模式执行正则表达式匹配操作。因此,这里所有的 RHS 都是正则表达式模式。

[[ $os =~ *el6* ]] && echo yes 不匹配,因为正则表达式为 *el6** 是一个量词,但您无法量化正则表达式的开头,因此它是无效的正则表达式。请注意,[[ $os =~ el6* ]] && echo yes 将打印 yes 因为 el6*el 匹配> 和 0+ 6 秒。

[[ $os =~ *".el6"也存在类似问题。 ]] && echo yes:正则表达式是*.el6.,并且它是无效的。

如果您想检查 .el6. 是否在字符串中,请使用 [[ $os = *".el6."* ]] && echo yes 。在这里,全局模式将为 *.el6.* 并且您需要 = 运算符。

关于与通配符匹配的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019795/

相关文章:

java - 包含字母数字和所有特殊字符(% 除外)的正则表达式

bash - 寻找匹配的 `'时出现意外的EOF

linux - bash下如何使用 "read"命令读取以<CR><LF>结尾的整行数据?

python - 在 Fabric 中如何从远程路径创建全局列表

java - 字符串的正则表达式,应允许 <String>(<String>,<String>), java 中的模式

regex - 在每个url末尾添加斜杠(需要重写nginx规则)

android - [^] 不工作的 SQLite 查询

bash - 如何在文件中使用 curl 命令数据?

php - 使用 PHP ftp_get() 检索具有通配 rune 件名的文件

bash - 和有什么不一样?和 Bash 中的 *?