Skip to main content
 首页 » 编程设计

c#之匹配 Url 的正则表达式,特定域除外

2024年02月27日35shihaiming

我有以下匹配 Url 的正则表达式。我想要做的是让它在 URL 属于某个域时不匹配,比方说 google.com。

我该怎么做?我一直在阅读其他问题和正则表达式引用,到目前为止我可以实现它。我的正则表达式:

^(https?:\/\/)?([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})([\/\w \.-]*)*\/?$ 

我用它来过滤聊天中的消息,我正在使用 C# 来执行此操作。如果您想进一步挖掘,这里有一个工具:http://regexr.com/3faji

C#扩展方法:

static class String 
{ 
    public static string ClearUrl(string text) 
    { 
        Regex regx = new Regex(@"^(https?:\/\/)?([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})([\/\w \.-]*)*\/?$", 
        RegexOptions.IgnoreCase); 
        string output = regx.Replace(text, "*"); 
 
        return output; 
 
    } 
} 

感谢您的帮助

请您参考如下方法:

您可以在正则表达式中使用否定前瞻来避免匹配某些域:

^(https?:\/\/)?(?!(?:www\.)?google\.com)([\da-zA-Z.-]+)\.([a‌​-zA-Z\.]{2,6})([\/\w .-]*)*\/?$ 

否则:

^(https?:\/\/)?(?!.*google\.com)([\da-zA-Z.-]+)\.([a‌​-zA-Z\.]{2,6})([\/\w .-]*)*\/?$ 

(?!(?:www\.)?google\.com) 是否定前瞻,当我们有 www.google.com 或 google.com 前面。

RegEx Demo