Netherwire
Netherwire

Reputation: 2787

Find substring divided by slashes

I need to find the substring that starts with a slash symbol and ends with a slash symbol.

string sourceStr = "assets/Level 1/diffuse;

The output of the regex must be "Level 1"

I found this regex ^"\"(.+)"\"$ but it seems like it doesn't works the way I wanted. Any ideas?

Upvotes: 0

Views: 103

Answers (4)

Nikunj.Patel
Nikunj.Patel

Reputation: 97

Instead of RegEx you can use String split function.

string strTestline = "This is /Test/. You can /test2/";
string[] strarray = strTestline.Split(new char[] { '/' });

foreach (string block in strarray)
{
     Console.WriteLine(block);
}

Upvotes: 0

JensB
JensB

Reputation: 6850

A though on how to make this work with any number of slashes so that only items contained inside two slashes are returned

https://dotnetfiddle.net/ErN9Wu

public static void Main()
{
    Console.Write("1 -> ");
    foreach(var w in getStringsInsideSlashes("a/b"))
        Console.Write(w + " - ");
    Console.WriteLine("");

    Console.Write("2 -> ");
    foreach(var w in getStringsInsideSlashes("a/b/c"))
        Console.Write(w + " - ");
    Console.WriteLine("");

    Console.Write("3 -> ");
    foreach(var w in getStringsInsideSlashes("a/b/c/d"))
        Console.Write(w + " - ");
    Console.WriteLine("");

    Console.Write("4 -> ");
    foreach(var w in getStringsInsideSlashes("a/b/c/d/"))
        Console.Write(w + " - ");
    Console.WriteLine("");

}

public static string[] getStringsInsideSlashes(string a){
    return a.Split('/').Skip(1).Take(a.Split('/').Count() -2).ToArray<string>();    
}

Output

1 -> 
2 -> b - 
3 -> b - c - 
4 -> b - c - d -

Upvotes: 0

captainsac
captainsac

Reputation: 2490

string[] sourceStrSplit = sourceStr.Split('/');

for(int i=1; i< sourceStrSplit.Length-1; i++)
{
   //All the sourceStrSplit[i] is what you required.
}

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You don't need regex for that. Just an old-school .Split() would be enough

Just do this:

string sourceStr = "assets/Level 1/diffuse";
var subStr = sourceStr.Split('/')[1];
Console.WriteLine(subStr); // Level 1 

Upvotes: 5

Related Questions