Search code examples
c#uriregex-group

Splite URI with regex


I am new in Regex. I want to splite my host URI like this:xxxPermanentWordChangeWord.myname.city.year.age i wnat to get: xxx and myname with one pattern regex

i tried this

var pattern = " (?=(?<p0>(.*)PermanentWord))?(?=(?<p1>i dont know what to write here in order to get myname))?";

Thanks!


Solution

  • According you question and sample there is what you want.

    The idea is:

    1. Get the string before PermanentWordChangeWord.. The rule for this is (.*)PermanentWordChangeWord\.

    2. Get the value after PermanentWordChangeWord. but before .(dot). The rule for this is ([^\..]*) this mean match all but without .(dot)

    var text = "xxxPermanentWordChangeWord.myname.city.year.age";
    var pattern = @"(.*)PermanentWordChangeWord\.([^\..]*)";
    Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
    Match match = reg.Match(text);
    
    var output = string.Empty;
    if (match.Success)
    {
        var group0 = match.Groups[0].Value; // This value is: xxxPermanentWordChangeWord.myname.city.year.age
        var group1 = match.Groups[1].Value; //This value is:  xxx
        var group2 = match.Groups[2].Value; //This value is: myname
    
        output = group1 + group2;
    }