使用或不使用尾部斜杠匹配 Url 模式的一部分

问题描述

我必须将模式与 URL 匹配。 我希望模式与域匹配,并且不关心它是否以斜杠结尾,或者它是否具有查询字符串参数或任何子域 我只想接受协议 http 或 https。

这是我尝试过的:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;   
using Newtonsoft.Json;
public class Program
{
    public static void Main()
    {
        List<string>  inputs = new List<string>{
            "https://dotnetfiddle.net/UA6bCb","http://www.test.ch/de-ch/apps/weve?anlassId=236601","https://www.test.ch/de-ch/apps/weve?anlassId=236601","http://test.ch/de-ch/apps/weve?anlassId=236601","https://test.ch/de-ch/apps/weve?anlassId=236601","https://test.chn/de-ch/apps/weve?anlassId=236601","https://www.test.chn/de-ch/apps/weve?anlassId=236601","https://test.ch/de-ch/","https://test.ch/de-ch","https://test.ch/","https://test.ch","https:test.ch"
        };
    
        Test(inputs);
        
    }

    public static void Test(List<string> inputs)
    {
        var regexString=  @"http(s)?://?([\w-]+\.)?test.ch(/[\w- ;,./?%&=]*)?";
        foreach(var input in inputs){
        var matches = Regex.Match(input,regexString,RegexOptions.Compiled | RegexOptions.IgnoreCase);
            
            if(matches.Success){
                Console.WriteLine("{0} matches {1}",input,regexString);
            }
            else{
                    Console.WriteLine("NO MATCH for {0}",input);
            }
        
        
        }
    }
}

返回

NO MATCH: https://dotnetfiddle.net/UA6bCb
Match: http://www.test.ch/de-ch/apps/weve?anlassId=236601
Match: https://www.test.ch/de-ch/apps/weve?anlassId=236601
Match: http://test.ch/de-ch/apps/weve?anlassId=236601
Match: https://test.ch/de-ch/apps/weve?anlassId=236601
Match: https://test.chn/de-ch/apps/weve?anlassId=236601
Match: https://www.test.chn/de-ch/apps/weve?anlassId=236601
Match: https://test.ch/de-ch/
Match: https://test.ch/de-ch
Match: https://test.ch/
Match: https://test.ch
NO MATCH: https:test.ch

问题是这个解决方案匹配https://test.chn/de-ch/apps/weve?anlassId=236601https:// /www.test.chn/de-ch/apps/weve?anlassId=236601

这应该是错误的,因为域以 chn 结尾。

我一直无法获得正确的正则表达式。

感谢您的帮助。

解决方法

如果您只想排除 file_ext,那么您可以使用负向后视来确保 test.chn 后面没有 ch

n

我添加了部分 "http(s)?://?([\w-]+\.)?test.ch(?!n)(/[\w- ;,./?%&=]*)?"