c0D3l0g1c
c0D3l0g1c

Reputation: 3164

Match text separated by SINGLE forward slash only

I am trying to split strings similar to this using Regex.Split:

To return this:

Effectively, ignoring double forward slash and only worrying about a single forward slash.

I know I should be using something like this /(?!/) negative look ahead - but can't get it to work.

This is not a duplicate of this Similar Question, because if you run that regular expression through Regex.Split, it does not give the required result.

Upvotes: 0

Views: 2257

Answers (3)

DirtyBit
DirtyBit

Reputation: 16772

As mentioned by @Panagiotis Kanavos in the comments section above, why make things complicated when you can use the Uri Class:

Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI.

public static void Main()
{
    Uri myUri = new Uri("https://www.linkedin.com/in/someone");   
    string host =  myUri.Scheme + Uri.SchemeDelimiter  + myUri.Host;
    Console.WriteLine(host);        
}

OUTPUT:

enter image description here

DEMO:

dotNetFiddle

Upvotes: 0

leofun01
leofun01

Reputation: 235

Also you can do it using this code :

string pattern = @"([^\/]+(\/{2,}[^\/]+)?)";
string input = @"https://www.linkedin.com/in/someone";
foreach(Match match in Regex.Matches(input, pattern)) {
    Console.WriteLine(match);
}

Output :

https://www.linkedin.com
in
someone

Upvotes: 0

Samantha
Samantha

Reputation: 975

How about this: (?<!/)/(?!/)

Breaking it down:

  • (?<!/): negative lookbehind for / characters
  • /: match a single / character
  • (?!/): negative lookahead for / characters

Taken together, we match a / character that does not have a / both before and after it.

Example usage:

string text = "https://www.linkedin.com/in/someone";
string[] tokens = Regex.Split(text, "(?<!/)/(?!/)");
foreach (var token in tokens)
{
    Console.WriteLine($"Token: {token}");
}

Output:

Token: https://www.linkedin.com
Token: in
Token: someone

Upvotes: 7

Related Questions