正则表达式

正则表达式基本元字符

1, .点表示除了/n以外的任意一个字符!注意当点在中口号中的时候如[.]它只表示一个点。

2,[]中括号表示范围如[0-9] [a-z] [A-Z]

3, ()小括号提升优先级和分组 

4,| 表示或者的意思,优先级别最低。

正则表达式限定符

1,+最少出现一次,最多出现无限次!

2,*最少出现0次,最多出现无限次!

3,?最少出现0次,最多出现一次,也就是要么出现,要么不出现,也成阻止贪婪模式!

4, {} {1,3}这样写表示最少出现一次,最多出现3次,{1,}这样写表示最少出现一次最多出现无限次!

正则表达式简便写法

1,d表示数字

2,D表示非数字

3,s表示空白符

4,S表示非空白符

5,w表示字母,数字,汉子

6,W表示特殊字符

7,^表示以什么开始或者是取非。[^0-9]表示非数字^[0-9]表示以数字开始。

8,$表示以什么结尾。 例如^[0-9][a-z]$表示以数字开头以字母结尾,比如1a,8d等等     开始和结束表示很严格的匹配

练习

身份证号的正则表达式匹配

身份证号有十五位与十八位的 十八位的身份证号最后一位有可能是x或者X。

[1-9][0-9]{14}|[1-9][0-9]{16}[0-9xX]

根据上面表达式可简写为:

[1-9][0-9]{14}([0-9]{2}[0-9xX])?

还可以较为严格的写出来

^[1-9][0-9]{14}([0-9]{2}[0-9xX])?$表示只需输入身份证号码即可!   例:如果你输入:“我的身份证号码是4552……555”,必须是直接输入身份证号码:“4552……555”!

邮箱的正则表达式匹配

14456555@asc.com或者1471—bjshj.@163.com.cn或者……

则正则表达式就可以写成:

[0-9a-zA-Z_.-]+@[0-9a-zA-Z_.]+([.][A-Za-z]+){1,2}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace _01使用正则表达式
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请您输入您的邮箱地址:");
            string email = Console.ReadLine();
            bool result = Regex.IsMatch(email,"[0-9a-zA-Z_.-]+@[0-9A-Za-z_.]+([.][A-Za-z]+){1,2}");//在此没有加上开始和结束
            Console.WriteLine(result);
            Console.ReadKey();

        }
    }
}

  

加上以什么开始和结束

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace _01使用正则表达式
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请您输入您的邮箱地址:");
            string email = Console.ReadLine();
            bool result = Regex.IsMatch(email,"^[0-9a-zA-Z_.-]+@[0-9A-Za-z_.]+([.][A-Za-z]+){1,2}$");//在此加上开始和结束
            Console.WriteLine(result);
            Console.ReadKey();

        }
    }
}

  

Regex的Match方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace _01使用正则表达式
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请您输入您的邮箱地址:");
            string email = Console.ReadLine();
            Match mt = Regex.Match(email,"[0-9a-zA-Z_.-]+@[0-9A-Za-z_.]+([.][A-Za-z]+){1,2}");
            Console.WriteLine(mt.Value);
            Console.ReadKey();

        }
    }
}

  

在这里要注意Match方法和ISMatch方法,要视情况而定!

感觉正则表达式应用的还是不是那么熟练今天把它书写下来加深记忆!

原文地址:https://www.cnblogs.com/lizanqirxx/p/5128263.html