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

How to use `expr` when there's an optional substring in the regex?

我想使用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 [a-w ]*go\([^ ]*\) .*

使用

.*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 :
--------------------------------------------------------------------------------
    [^[:space:]]*            any character except: whitespace
                             characters (0 or more times)
--------------------------------------------------------------------------------
  \)                       end of 
--------------------------------------------------------------------------------
                           ' '
--------------------------------------------------------------------------------
  .*                       any character (0 or more times)