简体   繁体   English

当正则表达式中有可选的 substring 时,如何使用“expr”?

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

I want to find the go[^ ]+ inside these two strings using expr .我想使用expr在这两个字符串中找到go[^ ]+ The output should be go1.17.6 and go1.18-becaeea119 . output 应该是go1.17.6go1.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

However, the devel part is optional and I can't figure out a way to properly ignore it with expr .但是, devel部分是可选的,我想不出一种方法来正确地忽略它expr

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

Using normal regexes, I would just (?: devel)?使用普通的正则表达式,我只会(?: devel)? it, but expr doesn't support ?它,但expr不支持? for some reason.由于某些原因。

Is there any way to achieve this using expr in one command?有没有办法在一个命令中使用expr来实现这一点?

is that what you wanted?那是你想要的吗?

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

Use利用

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

EXPLANATION解释

--------------------------------------------------------------------------------
  .*                       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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM