如何在 2nd 之后/之前捕获文本-zsh 中的符号

how to capture text after / but before 2nd - symbols in zsh

例如我有一个 git 分支名称 feature/ABC-123-my-stuff

我只想以这种格式捕获 ABC-123。

我试过了

cut -d "/" -f2 <<< "$branchName"

结果

ABC-123-my-stuff

但我只想保留 / 之后和第二个 -

之前的字符串

我要添加/修改什么才能实现该目标?

注意:我在 MacOS 上使用 zsh

使用正则表达式匹配:

 if [[ $branchName =~ /([^-]+-[^-]+)- ]]
 then
   desired_part=$match[1]
 else
   echo $branchName has not the expected format
 fi

使用cut 2次:

(cut -d"/" -f2 | cut -d"-" -f1,2) <<< $branchName

echo:

echo $branchName | cut -d"/" -f2 | cut -d"-" -f1,2

您可以使用的另一种方式 grep:

echo $branchName | egrep -o '[A-Z]{3}-[0-9]{3}'

注意:如果您每次有 3 次大写字母,然后是 -,然后是 3 位数字,此解决方案将有效。

所有解决方案都给我输出:

ABC-123