我想使用expr
找到这两个字符串中的go[^ ]+
。输出应该是1.17.6
和1.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([^ ]*) .*