当前位置: 移动技术网 > IT编程>开发语言>c# > c#使用正则表达式匹配字符串验证URL示例

c#使用正则表达式匹配字符串验证URL示例

2019年07月18日  | 移动技术网IT编程  | 我要评论
在system.text.regularexpression命名空间里,有正则表达式方法。复制代码 代码如下:using system.collections.generi

在system.text.regularexpression命名空间里,有正则表达式方法。

复制代码 代码如下:

using system.collections.generic;

using system.text;
using system.text.regularexpressions;

namespace regexdemo
{
    class program
    {
        static void main(string[] args)
        {
            regex regex = new regex("china", regexoptions.ignorecase);
            //使用match方法。
            string source = "china is my mother,my mother is china!";
            match m = regex.match(source);
            if (m.success)
            {
                console.writeline("找到第一个匹配");
            }
            console.writeline(new string('-',9));
            //下面的样例将演示使用matches方法进行匹配
            matchcollection matches=regex.matches(source);
            foreach(match s in matches)
            {
                if(s.success)
                    console.writeline("找到了一个匹配");
            }
            console.readline();
         }
    }
}
[/code]

复制代码 代码如下:

using system.collections.generic;
using system.text;
using system.text.regularexpressions;

namespace urlregex
{
    class program
    {
        static void main(string[] args)
        {
            string pattern = @"^(http|https|ftp)\://[a-za-z0-9\-\.]+\.[a-za-z]{2,3}(:[a-za-z0-9]*)?/?([a-za-z0-9\-\._\?\,\'/\\\+&$%\$#\=~])*$";
            regex r = new regex(pattern);
            string source = "//www.jb51.net";
            match m = r.match(source);
            if (m.success)
            {
                console.writeline("url验证成功!");
            }
            else
            {
                console.writeline("url验证失败!");
            }
            console.readline();
        }
    }
}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网