当正则表达式中有可选的子字符串时如何使用"expr"?



我想使用expr找到这两个字符串中的go[^ ]+。输出应该是1.17.61.18-becaeea119

go version go1.17.6 linux/amd64
go version devel go1.18-becaeea119 Tue Dec 14 17:43:51 2021 +0000 linux/amd64

然而,devel部分是可选的,我无法找到用expr正确忽略它的方法。

expr "$(go version)" : ".*go version go([^ ]*) .*"
expr "$(go version)" : ".*go version devel go([^ ]*) .*"

使用普通正则表达式,我只需要(?: devel)?,但由于某种原因,expr不支持?

有没有办法在一个命令中使用expr来实现这一点?

使用

.*go version.* go([^[:space:]]*) .*

解释

--------------------------------------------------------------------------------
.*                       any character (0 or more times)
--------------------------------------------------------------------------------
go version               'go version'
--------------------------------------------------------------------------------
.*                       any character (0 or more times)
--------------------------------------------------------------------------------
go                      ' go'
--------------------------------------------------------------------------------
(                       group and capture to 1:
--------------------------------------------------------------------------------
[^[:space:]]*            any character except: whitespace
characters (0 or more times)
--------------------------------------------------------------------------------
)                       end of 1
--------------------------------------------------------------------------------
' '
--------------------------------------------------------------------------------
.*                       any character (0 or more times)

这就是您想要的吗?

.*go version [a-w ]*go([^ ]*) .*

相关内容

  • 没有找到相关文章