Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take uniqueId or packageName form app-store or play market url with the help of C# regular expressions?

Tags:

c#

regex

I have the following function to take packageName or unicueId for Google Play market or Apple App Store URL:

string GetPackageNameFromUrl(string url)
{
    string res = "";

    string patternAndroid = @"^https:\/\/play\.google\.com\/store\/apps\/details\?id=(.+)\&.+";
    Regex regexpAndroid = new Regex(patternAndroid, RegexOptions.Compiled);

    if (regexpAndroid.IsMatch(url))
    {
        res  = regexpAndroid.Matches(url).FirstOrDefault()?.ToString();
    }

    string patternIos = @"^https:\/\/apps\.apple\.com\/ru\/app\/.+\/id(\d+)\?.+";
    Regex regexpIos = new Regex(patternIos, RegexOptions.Compiled);


    if (regexpIos.IsMatch(url))
    {
        res = regexpIos.Matches(url).ToList().FirstOrDefault()?.ToString();
    }

    return res;
}

example of Play market URL: https://play.google.com/store/apps/details?id=com.zhiliaoapp.musically&hl=ru

example of IOS App store URL is: https://apps.apple.com/ru/app/%D1%8F%D0%BD%D0%B4%D0%B5%D0%BA%D1%81-%D0%BD%D0%B0%D0%B2%D0%B8%D0%B3%D0%B0%D1%82%D0%BE%D1%80-gps-%D0%BF%D1%80%D0%BE%D0%B1%D0%BA%D0%B8/id474500851?v0=WWW-EURU-ITSTOP100-FREEAPPS&l=ru&ign-mpt=uo%3D4

I need to catch this (if URL is play market URL) com.zhiliaoapp.musically or this (if IOS) 474500851 and return it as string. But my function returns whole given URL. I can't catch mistake. Where is the mistake?

like image 920
Aleksej_Shherbak Avatar asked Oct 27 '25 17:10

Aleksej_Shherbak


2 Answers

Just go for a simple regex capturing the id parameter or the id pattern:

(id(\d+)|id=([\w.]+))

Regex 101 link with your examples : https://regex101.com/r/T1K4a7/1

like image 116
Oflocet Avatar answered Oct 29 '25 06:10

Oflocet


You could use a single capturing group. Match id, and optional equals sign and then capture in group 1 matching any character except a &or?` using a negated character class.

id=?([^&?]+)

Regex demo

like image 28
The fourth bird Avatar answered Oct 29 '25 07:10

The fourth bird