在线工具 在线编程 在线白板 在线工具 在线编程 在线白板

asp.net 正则表达式验证http://

大神们哪位知道,asp.net 正则表达式验证http://?

我在做友情链接的添加,现在遇到的问题是要判断url里面输入的地址
是否以http://开头,如果没有就
http://+url
地址,如果有就直接用url地址
不知道正则表达式怎么写?求高人帮忙写下
protected void Button1_Click(object sender, EventArgs e)
{
string url=txtAddress.Text;

}
最新回答
≮陌路≯七

2025-03-27 01:28:52

楼上两位的表达式都是对的.. 在此借二位的光,借花献佛了..

二楼解法正确,不过如果用Regex的Replace方法处理, 代码会更简练一些 .

        private void button1_Click(object sender, EventArgs e)
        {
            Regex reg = new Regex("^(?<!=http://)([\\w-]+\\.)+[\\w-]+(/[\\w-\\./?%=]*)?");
            String strURL = ""; //txtAddress.Text;

            strURL = "
http://www.baidu.com
";//这个URL是以"http://"开头的.
            strURL = reg.Replace(strURL, "
http://$0
");
            MessageBox.Show(strURL);  //显示结果 : 
http://www.baidu.com


            strURL = "
www.baidu.com
"; //修改为不以"http://"开头的. 
            strURL = reg.Replace(strURL, "
http://$0
");
            MessageBox.Show(strURL);  //显示结果 : 
http://www.baidu.com
 
        }

所以楼主关於URL的是不是用"http://"开头的那个问题, 直接用下边的两句就可以实现了.

        protected void Button1_Click(object sender, EventArgs e)
        {
            Regex reg = new Regex("^(?<!=http://)([\\w-]+\\.)+[\\w-]+(/[\\w-\\./?%=]*)?");
            string url = reg.Replace(txtAddress.Text, "
http://$0
");  
        } 
猫街少女

2025-03-27 00:10:19

http://([\w-]+\.)+[\w-]+(/[\w-\./?%=]*)?

明白了吗?用正则表达式。
具体这样做

protected void Button1_Click(object sender, EventArgs e)
{
string url=txtAddress.Text;
string s = @"http://([\w-]+\.)+[\w-]+(/[\w-\./?%=]*)?";
Regex reg = new Regex(s);
Match mch = reg.Match(url);
if (mch.Success)
{
//这是以 http:// 开头的
}
else
{
//这不是以 http:// 开头的
}
}

当然,你的添加引用。
using System.Text.RegularExpressions;
课桌上刻着我们的青春

2025-03-27 01:32:29

http://([\w-]+\.)+[\w-]+(/[\w-\./?%=]*)?