【问题标题】:Match part of Url pattern with or withour trailing slash匹配带有或不带有斜杠的 Url 模式的一部分
【发布时间】:2021-03-02 14:36:55
【问题描述】:

我必须将模式与 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 结尾。

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

感谢您的帮助。

【问题讨论】:

  • 使用锚点。见regex101.com/r/PrYANW/1
  • var regexString= @"http(s)?://?([\w-]+\.)?test.ch/([\w- ;,./?%&= ]*)?";
  • @azuremycry 谢谢,但这也不起作用,因为这会导致 test.ch 不匹配,但如上所述,我需要它能够带有或不带有斜杠
  • 您的问题的答案是:var regexString= @"http(s)?://?([\w-]+\.)?test.ch(/|$)([\ w- ;,./?%&=]*)?";
  • 但请告诉我我的解决方案是否适合您:)?

标签: c# regex


【解决方案1】:

如果您只想排除test.chn,那么您可以使用否定的lookbehind 来确保ch 后面没有n

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

我添加了(?!n)的部分。

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2011-12-14
    相关资源
    最近更新 更多