peter
peter

Reputation: 2103

Regex for substring between two known tags that might appear more than once

From a string like this

http://a.b.c.d:1521/myApp/unreachable.stream/manifest.f4m?DVR

how would I extract only the part between ".stream" and the first occurence of "/" before the ".stream" with a regex, e.g. "unreachable" in above example?

Upvotes: 1

Views: 82

Answers (3)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

There is no need for regex:

string result = url.Split('/').Where(s => s.EndsWith(".stream"))
                     .Select(s => s.Substring(0, s.Length - 7 /*".stream".Length*/)
                     .FirstOrDefault();

If you must use regex:

string regex = "([^/]+?)\\.stream";

http://fiddle.re/cyy8d

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

Here's an example with regex:

var match = Regex.Match(myStr, @"/([^/]+)\.stream\b");
string extracted = match.Groups[1].Value;
Console.WriteLine(extracted); // "unreachable"

Upvotes: 3

dav_i
dav_i

Reputation: 28107

Well if your input is going to be URIs like that...

var uri = new Uri(@"http://a.b.c.d:1521/myApp/unreachable.stream/manifest.f4m?DVR");

var streamSegment = uri.Segments.FirstOrDefault(a => a.Contains(".stream")) ?? "";

var result = streamSegment.Split('.').First().Dump();

Upvotes: 1

Related Questions