Home > Software design >  Regex to retrieve after first slash and next slash only
Regex to retrieve after first slash and next slash only

Time:12-29

If I have a web url with following https://github.com/myorg/myrepo.git

How can I retrieve only between the first and second slash "myorg" using regex ?

I have looked up few and only found the how to retrieve last piece using | sed 's#.*/##'

CodePudding user response:

Not a regex but very simple

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

Slightly more flexible as it get's the next to last field:

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

CodePudding user response:

Using Bash's builtin Regex engine:

#!/usr/bin/env bash
url='https://github.com/myorg/myrepo.git'

if [[ $url =~ github.com/([^/] )/ ]]; then
  printf '%s\n' "${BASH_REMATCH[1]}"
fi

Using POSIX-shell grammar variable expansion:

#!/usr/bin/env sh

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

CodePudding user response:

You, my friend, can use lookaheads e lookbehinds

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

this code it will get everything between slashs

  • Related