Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmExtracting Repository Name from a Given GIT URL using Regular Expressions

Extracting Repository Name from a Given GIT URL using Regular Expressions

Given a string str, the task is to extract Repository Name from the given  GIT URL.

Examples:

GIT URL can be any of the formats mentioned below:

Input: str=”git://github.com/book-Store/My-BookStore.git”
Output: My-BookStore
Explanation: The Repo Name of the given URL is: My-BookStore

Input: str=”git@github.com:book-Store/My-BookStore.git”
Output: My-BookStore
Explanation: The Repo Name of the given URL is: My-BookStore

Input: str=”https://github.com/book-Store/My-BookStore.git”
Output: My-BookStore
Explanation: The Repo Name of the given URL is: My-BookStore

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the Repo Name as written: regex = “([^/]+)\.git$“

Follow the below steps to implement the idea:

  • Create a regex expression to extract aRepo Name  from the string.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to find.

Below is the code implementation of the above-discussed approach:

C++14




// C++ code for the above approach:
#include <bits/stdc++.h>
#include <regex>
 
using namespace std;
 
// Function to extract Repo Name
// from a given string
void extractRepositoryName(string str) {
     
    // You can Add n number of GIT URL
    // formats in the below given
    // String Array.
    string strPattern[] = {"([^/]+)\.git$"};
    for (int i = 0; i < sizeof(strPattern)/sizeof(strPattern[0]); i++) {
        regex pattern(strPattern[i]);
        auto words_begin = sregex_iterator(str.begin(), str.end(), pattern);
        auto words_end = sregex_iterator();
        for (sregex_iterator i = words_begin; i != words_end; ++i) {
            smatch match = *i;
            cout << match.str() << endl;
        }
    }
}
 
// Driver Code
int main() {
     
    // String int the form of GIT URL
    cout << "Given GIT URL is:\n" << str << endl;
    cout << "Repository Name of above given GIT URL is:" << endl;
    extractRepositoryName(str);
 
    return 0;
}
 
// This Code is Contributed by Prasad Kandekar(prasad264)


Java




// Java code for the above approach
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // String int the form of GIT URL
        String str
            = "git:/"
              + "/github.com/book-Store/My-BookStore.git";
        System.out.println(" Given GIT URL is:\n" + str);
        System.out.println(
            "Repository Name of above given GIT URL is:");
        extractRepositoryName(str);
    }
 
    // Function to extract Repo Name
    // from a given string
    static void extractRepositoryName(String str)
    {
 
        // You can Add n number of GIT URL
        // formats in the below given
        // String Array.
        String strPattern[] = { "([^/]+)\\.git$" };
        for (int i = 0; i < strPattern.length; i++) {
            Pattern pattern
                = Pattern.compile(strPattern[i]);
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
}


Python3




import re
 
# Function to extract Repo Name from a given string
def extractRepositoryName(str):
   
    # You can Add n number of GIT URL formats in the below given
    # String Array.
    strPattern = ["([^/]+)\\.git$"]
    for i in range(len(strPattern)):
        pattern = re.compile(strPattern[i])
        matcher = pattern.search(str)
        if matcher:
            print(matcher.group(1))
 
# Driver Code
str = "git:/github.com/book-Store/My-BookStore.git"
print("Given GIT URL is:\n", str)
print("Repository Name of above given GIT URL is:")
extractRepositoryName(str)


C#




using System;
using System.Text.RegularExpressions;
 
class Program
{
  static void Main(string[] args)
  {
 
    // String in the form of GIT URL
    string str = "git:/" + "/github.com/book-Store/My-BookStore.git";
    Console.WriteLine(" Given GIT URL is:\n" + str);
    Console.WriteLine("Repository Name of above given GIT URL is:");
    ExtractRepositoryName(str);
  }
 
 
  static void ExtractRepositoryName(string str)
  {
     
    // You can Add n number of GIT URL
    // formats in the below given
    // String Array.
    string[] strPattern = { "([^/]+)\\.git$" };
    for (int i = 0; i < strPattern.Length; i++)
    {
      Regex pattern = new Regex(strPattern[i]);
      MatchCollection matches = pattern.Matches(str);
      foreach (Match match in matches)
      {
        Console.WriteLine(match.Value);
      }
    }
  }
}


Javascript




// Function to extract Repo Name from a given string
function extractRepositoryName(str) {
  // You can Add n number of GIT URL formats in the below given
  // String Array.
  let strPattern = ["([^/]+)\\.git$"];
  for (let i = 0; i < strPattern.length; i++) {
    let pattern = new RegExp(strPattern[i]);
    let matcher = pattern.exec(str);
    if (matcher) {
      console.log(matcher[1]);
    }
  }
}
 
// Driver Code
let str = "git:/github.com/book-Store/My-BookStore.git";
console.log("Given GIT URL is:\n" + str);
console.log("Repository Name of above given GIT URL is:");
extractRepositoryName(str);


Output

 Given GIT URL is:
git://github.com/book-Store/My-BookStore.git
Repository Name of above given GIT URL is:
My-BookStore.git

Complexity :

The time complexity of the above code depends on the size of the input string and the number of patterns in the strPattern array. Assuming the input string size is n and the number of patterns in strPattern is m, then the time complexity can be approximated as O(m*n) due to the nested loop and the regular expression matching operation

The space complexity of the above code is O(m) because it only stores the patterns in the strPattern array and does not create any additional data structures that depend on the input string size.

Related Articles:

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments