【问题标题】:URL Regex in Visual Studio Winforms C#Visual Studio Winforms C# 中的 URL 正则表达式
【发布时间】:2015-07-18 15:13:12
【问题描述】:

我想使用正则表达式来验证在我的文本框 txtWeb 中输入的 URL,但是我发现的所有正则表达式在 Visual Studio 2013 中都不起作用。错误是由所有反斜杠和点引起的。不知道有没有办法让它工作?这是我要使用的正则表达式:

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

这就是我尝试使用它的方式:

if (txtWeb.Text != "")
            {
                Regex regex = new Regex("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/");
                Match match = regex.Match(txtWeb.Text);
                if (!match.Success)
                {
                    MetroMessageBox.Show(this, "Ce site web est invalide", "Message d'erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    erreur = false;
                }
            }

【问题讨论】:

    标签: c# regex winforms visual-studio-2013


    【解决方案1】:

    去掉开头和结尾处存在的正斜杠,也使用逐字字符串,这样就不需要转义所有的反斜杠了..

    Regex regex = new Regex(@"^(https?://)?([\da-z.-]+)\.([a-z\.]{2,6})([/\w .-]*)/?$");
    

    这是一个 c# 正则表达式,而不是 js 或 perl,其中正则表达式模式可以包含在正斜杠中,例如,

    /foo/
    

    为了性能,我只是将([\/\w \.-]*)*修改为([\/\w \.-]*)

    【讨论】:

    • 它是用于 C# 的,有了你的回答,它现在可以工作了,感谢 Avinash 的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多