与えられた文字列
http://stackoverflow.com/questions/ask/index.php
(.*?)
…3番目のスラッシュと最後のスラッシュの間のサブストリングを取得したい。
questions/ask
C#の正規表現でこれを実現するにはどうすればよいですか?
Uri uri = new Uri("http://stackoverflow.com/questions/ask/index.php");
string result = uri.Segments[1] + uri.Segments[2];
result = result.Remove(result.Length - 1);
Console.WriteLine(result);
Uri.Segments
あなたはプロパティを見ることができます
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0],
uriAddress1.Segments[1], uriAddress1.Segments[2]);
次の出力を生成します。
The parts are /, title/, index.htm
Uri url = new Uri("http://stackoverflow.com/questions/ask/index.php");
string s = string.Join("", url.Segments.Take(url.Segments.Length - 1)).Trim('/');
これを行う適切な方法は、Uriオブジェクトを使用することです。
Uri u = new Uri("http://stackoverflow.com/questions/ask/index.php");
string[] s = u.Segments;
文字列照合や正規表現の代わりに、既存のUriクラスとPathクラスを使用してみてください。何かのようなもの:
Path.GetDirectoryName(new Uri(url).AbsolutePath)
他の答えは行く方法です。しかし、まだ正規表現を探している場合は、これでうまくいくはずです。
([^/]*/[^/]*)/[^/]*$
あなたが探しているパスは最初のサブマッチにあります。