开发者

C# Regular Expressions, text between slash

开发者 https://www.devze.com 2023-03-01 02:54 出处:网络
I have 3 type of strings in C#, i want to retrieve text between slash(es) using Regular Expressions string type1 = \"www.domain.com/category-name/1.html\";

I have 3 type of strings in C#, i want to retrieve text between slash(es) using Regular Expressions

string type1 = "www.domain.com/category-name/1.html";

string type2 = "www.domain.com/category-name/sub-category-name/2.html";

string type3 = "www.domain.com/category-name/sub-category-name/sub-sub-category-name/3.html";

Q1) From type1 variable i want to retrieve text between first and second slash '/'. i should get category-name.

Q2) From type2 variable i want to retrieve text between first and second slash '/', and text between second and third slash '/'. i should get category-name and sub-category-name

Q3) From type3 variable i want to retrieve text between first and second slash '/', and text between second and third slash '/', and text between third开发者_StackOverflow社区 and fourth slash '/'. i should get category-name and sub-category-name and sub-sub-category-name

Any help will be appreciated

Thanks


You don't need a regular expression for this to work, have a look at the String.Split method and the StringSplitOptions enum.

string type1 = "www.domain.com/category-name/1.html";
string[] splicedUrl = type1.Split('/', StringSplitOptions.None);

if (splicedUrl.length > 0)
{
    // Access the correct index, check how many entries the array has etc.
}

You might want to have a look at the following post.


Assuming theString is the variable you want to parse:

var tokens = theString.split('/');
if(tokens.length >= 2)
{
    string category = tokens[1];

    List<string> subCategories = new List<string>();
    for(int k = 2; k < tokens.length - 1; k++)
    {
        subCategories.Add(tokens[k]);
    }
}


You can also do something like below using System.Uri:

Uri type1 = new Uri("http://www.domain.com/category-name/1.html");
var categoryNameType1 = type1.Segments[1];
Uri type2 = new Uri("http://www.domain.com/category-name/sub-category-name/2.html");
var categoryNameType2 = type2.Segments[1];
var subcategoryNameType2 = type2.Segments[2];

This might be slightly more complex than a simple string.Split() but if you need to get more out of a URI like a query, you can easily get it.


If you really feel the need to (mis)use a regular expression in this case

/([\w-]+)(?=/)

should do the trick. This assumes that the items between the slashes are letters and hyphens.


Here's another way of doing this. It is equivalent of other answers you already have, but just wanted to post it because it is slightly different:

string url = "www.domain.com/category-name/1.html"
var splitted = url.Split('/');
var values = splitted.Skip(1).Take(splitted.Length - 2).ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消