微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用或不使用尾部斜杠匹配 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- ;,./?%&=]*)?"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。