Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于匹配.html之前和之后文本的正则表达式/_C#_.net_Regex_Url - Fatal编程技术网

C# 用于匹配.html之前和之后文本的正则表达式/

C# 用于匹配.html之前和之后文本的正则表达式/,c#,.net,regex,url,C#,.net,Regex,Url,用这根绳子 http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html 我需要以 用这个 hellow-1/yo sdf.html 我需要yo sdf这应该能满足您的需要: Regex re = new Regex(@"/([^/]*)\.html$"); Match match = re.Match("http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html"); Console.WriteLine(match.Groups[1].Valu

用这根绳子

http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html

我需要以

用这个

hellow-1/yo sdf.html


我需要
yo sdf

这应该能满足您的需要:

Regex re = new Regex(@"/([^/]*)\.html$");
Match match = re.Match("http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html");
Console.WriteLine(match.Groups[1].Value); //Or do whatever you want with the value
这需要
使用System.Text.RegularExpressions

尝试以下操作:

using System.Text.RegularExpressions;
Regex pattern = new Regex(".*\/([a-z\-]+)\.html");
Match match = pattern.Match("http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html");
if (match.Success)
{
    Console.WriteLine(match.Value);
}
else
{
    Console.WriteLine("Not found :(");
}
string url = "http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html";
Match match = Regex.Match(url, @"/([^/]+)\.html$");
if (match.Success)
{
    string result = match.Groups[1].Value;
    Console.WriteLine(result);
}
结果:

sdf-as 自卫队
但是,最好使用类来解析字符串,以便正确处理
http://example.com/foo.html?redirect=bar.html

此选项使斜杠和点部分可选,并允许文件具有任何扩展名:

newregex(@“^(.*/)?(?[^/]*?)(\.[^/]*)?$”,RegexOptions.ExplicitCapture)


但是我仍然更喜欢子字符串(LastIndexOf(…),因为它更可读。

有很多方法可以做到这一点。下面使用lookarounds仅匹配文件名部分。如果出现以下情况,则实际上不允许使用
/

string[] urls = {
   @"http://sfsdf.com/sdfsdf-sdfsdf/sdf-as.html",
   @"hellow-1/yo-sdf.html",
   @"noslash.html",
   @"what-is/this.lol",
};

foreach (string url in urls) {
   Console.WriteLine("[" + Regex.Match(url, @"(?<=/|^)[^/]*(?=\.html$)") + "]");
}
模式的工作原理 共有3个部分:


  • (?
    /^.*\/([a-z\-]+)\.html$/
    我将把C#的细节留给您。+1,还有什么不可以,谢谢?
    [sdf-as]
    [yo-sdf]
    [noslash]
    []
    
    static String getFilename(String url, String ext) {
       if (url.EndsWith(ext)) {
         int k = url.LastIndexOf("/");
         return url.Substring(k + 1, url.Length - ext.Length - k - 1);
       } else {
         return "";
       }
    }
    
    getFilename(url, ".html")