【问题标题】:Regex to retrieve after first slash and next slash only正则表达式仅在第一个斜杠和下一个斜杠后检索
【发布时间】:2022-01-27 11:34:18
【问题描述】:

如果我有一个带有以下https://github.com/myorg/myrepo.git 的网址

如何使用正则表达式仅在第一个和第二个斜杠“myorg”之间检索?

我查了几个,只找到了如何使用| sed 's#.*/##'检索最后一块

【问题讨论】:

  • 试试这个:sed 's#[^/]*//[^/]*/\([^/]*\).*#\1#' <<< 'https://github.com/myorg/myrepo.git'。顺便说一句,第一个和第二个斜杠之间是空字符串。您可能想要在第二个和第三个斜杠之间。
  • 这对我有用,谢谢

标签: regex bash shell


【解决方案1】:

不是正则表达式,但非常简单

echo https://github.com/myorg/myrepo.git | awk -F\/ '{print $4}'

稍微灵活一点,因为它是倒数第二个字段:

echo https://github.com/myorg/myrepo.git | awk -F\/ '{print $(NF-1)}'

【讨论】:

    【解决方案2】:

    使用 Bash 的内置 Regex 引擎:

    #!/usr/bin/env bash
    url='https://github.com/myorg/myrepo.git'
    
    if [[ $url =~ github.com/([^/]+)/ ]]; then
      printf '%s\n' "${BASH_REMATCH[1]}"
    fi
    

    使用POSIX-shell语法变量扩展:

    #!/usr/bin/env sh
    
    url='https://github.com/myorg/myrepo.git'
    t="${url#*github.com/}"
    org="${t%%/*}"
    printf '%s\n' "$org"
    

    【讨论】:

      【解决方案3】:

      你,我的朋友,可以使用前瞻和后瞻

      (?<=\.com\/).+(?=\/)
      

      这段代码将得到斜线之间的所有内容

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2020-05-15
      • 2011-04-19
      • 1970-01-01
      • 2021-11-18
      • 2011-03-09
      • 1970-01-01
      • 2011-08-09
      相关资源
      最近更新 更多