简体   繁体   中英

URL Regex in Visual Studio Winforms C#

I want to use a Regular Expression to validate the URL entered in my textbox txtWeb , however all Regular Expressions I've found doesn't work in Visual Studio 2013. The errors is caused by all the backslashes and dots. I don't know if there's a solution to make it working? Here's the Regex that I want to use :

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

And here's how I'm trying to use it :

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;
                }
            }

Remove the forward slashes exists at the start and end and also use verbatim string, so that you don't need to escape all the backslashes..

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

This is ac# regex, not js or perl where the regex pattern could be included within forward slashes like,

/foo/

For the sake of performance, I just modified ([\\/\\w \\.-]*)* to ([\\/\\w \\.-]*)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM