How to conditional regex

前端 未结 4 483
无人及你
无人及你 2020-12-31 14:53

I want a regex that does one thing if it has 3 instances of .in the string, and something else if it has more than 3 instances.

for example



        
4条回答
  •  耶瑟儿~
    2020-12-31 15:29

    You don't need Regex for this (as for many other common tasks).

    public static string AbsolutePathToSubdomain(this Uri uri, string subdomain)
    {
        // Pre-process the new subdomain
        if (subdomain == null || subdomain.Equals("www", StringComparison.CurrentCultureIgnoreCase))
            subdomain = string.Empty;
    
        // Count number of TLDs (assume at least one)
        List parts = uri.Host.Split('.').ToList();
        int tldCount = 1;
        if (parts.Count >= 2 && parts[parts.Count - 2].Length <= 3)
        {
            tldCount++;
        }
    
        // Drop all subdomains
        if (parts.Count - tldCount > 1)
            parts.RemoveRange(0, parts.Count - tldCount - 1);
    
        // Add new subdomain, if applicable
        if (subdomain != string.Empty)
            parts.Insert(0, subdomain);
    
        // Construct the new URI
        UriBuilder builder = new UriBuilder(uri);
        builder.Host = string.Join(".", parts.ToArray());
        builder.Path = "/";
        builder.Query = "";
        builder.Fragment = "";
    
        return builder.Uri.ToString();
    }
    

提交回复
热议问题