.NET高级技术_04正则、序列化、XML

一:正则表达式

正则表达式是对字符串进行匹配的语法。像select * from t where name like '%张%'一样,定义了一些特殊的“元字符”,用来判断一个字符串是否满足某个规则。正则表达式非常深,编译器都是基于正则表达式,掌握基本使用即可。

基本元字符

1、.表示除了\n以外的任意的单个字符;
2、[0-9]表示的是0到9之间任何一个整数数字;[a-z]任意一个小写字母;[A-Z]任意一个大写字母;
3、\d数字;\D非数字;\s空白;\S非空白;\w小写字母和数字和汉字;\W特殊符号。正则表达式中的\是真的\;
4、\表示对于.等特殊字符转义;
5、()提升优先级别和提取组;
6、[]代表一个区间中的任意一个[abc\d]就代表abc或者数字中的任意一个字符
7、| 或者;
8、+是出现1次到无限次;
9、*是出现0次到无限次;
10、?是出现0次到1次;
11、{5}出现5次,{1,2}一次或两次,{5,8}为5至8次,{1,}最少一次,{3,}最少3次;
12、^以…开始,$以…结束;

使用Regex.IsMatch(被匹配字符串,正则表达式)判断是否匹配。C#中表示正则表达式最好前面加上@,可以避免转义带来的困扰。

常见正则表达式

1、这样写是有缺陷的Regex.IsMatch("18911111234", @"\d{11}")、Regex.IsMatch("3333333333333333", @"\d{11}"),应该使用^$改成Regex.IsMatch("18911111234333", @"^\d{11}$")2、手机号:@"^1\d{10}$"3@"^\d{5,10}$"匹配QQ号;

4、ipv4地址:@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"正则表达式很难“一步到位”。192.168.1.155@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" 匹配邮箱;

6[\u4e00-\u9fa5]  单个汉字;@"^[\u4e00-\u9fa5]{2,4}$" 长度为2-4的汉字姓名;

7、身份证号(15位、18位数字)@"^(\d{15})$|^(\d{18})$"

8、身份证号(18位,最后一位可能是x)@"^(\d{17})[\dxX]$"

9、日期格式:"^\d{4}\-\d{1,2}\-\d{1,2}$" 
namespace NS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //bool b1 = Regex.IsMatch("123","\\d{3}");
            bool b2 = Regex.IsMatch("123", @"\d{3}");
            bool b3 = Regex.IsMatch("123b1", @"\d{3}");  //有一部分匹配即可,返回true
            bool b4 = Regex.IsMatch("123", @"^\d{3}$");  //完全匹配
            Console.WriteLine(b4);
            Console.WriteLine(Regex.IsMatch("13812349876", @"^1\d{10}$"));
            Console.WriteLine(Regex.IsMatch("192.168.1.1", @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"));
            Console.WriteLine(Regex.IsMatch("蛋", "[\u4e00-\u9fa5]"));

            Match match = Regex.Match("2015-01-10", @"^(\d{4})-(\d{1,2})-(\d{1,2})$");
            if (match.Success)
            {
                string year = match.Groups[1].Value;  //注意序号从1开始
                string month = match.Groups[2].Value;
                string day = match.Groups[3].Value;
                Console.WriteLine("年:" + year + " 月:" + month + " 日:" + day);
            }

            Console.ReadLine();
        }
    }
}

二:对象序列化(二进制序列化)

简介

对象序列化是将对象转换为二进制数据(字节流),反序列化是将二进制数据还原为对象。对象是稍纵即逝的,不仅程序重启、操作系统重启会造成对象的消失,就是退出函数范围等都可能造成对象的消失,序列化/反序列化就是为了保持对象的持久化。

BinaryFormatter类有两个方法:
void Serialize(Stream stream, object pbj)
对象obj序列化到Stream中
object Deserialize(Stream stream)
将对象从stream中反序列化,返回值为反序列化得到的对象

namespace NS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person();
            p1.Name = "lilei";
            p1.Age = 10;

            BinaryFormatter binForm = new BinaryFormatter();
            using (FileStream fs = File.OpenWrite("d:/1.data"))
            {
                binForm.Serialize(fs, p1);

            }

            BinaryFormatter binForm2 = new BinaryFormatter();
            using (FileStream fs = File.OpenRead("d:/1.data"))
            {
                Person p2 = binForm2.Deserialize(fs) as Person;
                Console.WriteLine("姓名:" + p2.Name + ", 年龄:" + p2.Age);
            }

            Console.ReadLine();
        }
    }

    [Serializable]
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

三:对象序列化的一些注意事项

要序列化的类型必须标记为:[Serializable]
该类型的父类也必须标记为:[Serializable]
该类型中的所有成员的类型也必须标记为:[Serializable]

序列化只会对类中的字段序列化,(只能序列化一些状态信息)
类结构修改后之前序列化的内容尽量不要用了,否则可能会出错;

为什么要序列化?

保持对象的持久化,将一个复杂的对象转换流,方便我们的存储与信息交换

应用:ASP.net中进程外Session要求对象可序列化;

还有Xml序列化,应用开发中Json序列化已经代替了二进制序列化和Xml序列化等

面试题:类可序列化的条件是?

答:这个类必须标记为Serializable,如果这个类有父类,那父类也必须要编辑为Serialzable类型的,如果这类所有成员的也必须要编辑为Serializable。

四:XML基本使用

简介(可扩展标记语言)

XML优点:容易读懂;格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写。
XML就是用一种格式化的方式来存储数据,我们可以通过用记事本打开。
.net程序中的一些配置文件app.config、web.config文件都是XML文件。

XML语法规范:标签/节点(Tag/Node)、嵌套(Nest)、属性。标签要闭合,属性值要用""包围,标签可以互相嵌套。

XML树,父节点、子节点、兄弟节点(siblings)。

XML编写完成以后可以用浏览器来查看,如果写错了浏览器会提示。如果明明没错,浏览器还是提示错误,则可能是文件编码问题。

<Person>
  <!--StuID = "1" 是属性-->
  <Student StuID = "1">
    <!--"张三"是内容-->
    <StuName > 张三 </StuName >  
  </Student >
  <Student StuID = "2">
    <StuName> 李四 </StuName>
	<StuAge Age = "10" />
  </Student>
</Person>

XML语法特点

1、严格区分大小写;
2、有且只能有一个根节点;
3、有开始标签必须有结束标签,除非自闭合:
4、属性必须使用双引号;
5、(可选)文档声明:<?xml version="1.0" encoding="utf-8"?>
6、注释:
7、注意编码问题,文本文件实际编码要与文档声明中的编码一致。

XML文件读取

namespace NS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(@"d:\ceshi.xml");  //加载xml文件
            XmlNodeList xmlNodeList = xmlDocument.DocumentElement.ChildNodes;  //节点集合
            foreach (XmlNode node in xmlNodeList)
            {
                XmlElement xmlElement = (XmlElement)node;
                string stuID = xmlElement.GetAttribute("StuID");
                Console.WriteLine("Student的StuID属性值为:" + stuID);
                XmlNode cnode = xmlElement.SelectSingleNode("StuName");
                string stuName = cnode.InnerText;
                Console.WriteLine("StuName的文本内容为:" + stuName);
            }
            Console.ReadKey();
        }
    }
}

XML文件生成

namespace NS
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Person[] persons = { new Person(1, "lilei", 20), new Person(2, "hanmeimei", 10), new Person(3, "polly", 30) };
            XmlDocument doc = new XmlDocument();
            XmlElement ePersons = doc.CreateElement("Persons");  //创建根节点
            doc.AppendChild(ePersons);  //添加根节点:将Persons添加为文档的子节点,由于文档还没有子节点,所以这个节点就作为根节点
            foreach (Person person in persons)
            {
                XmlElement ePerson = doc.CreateElement("Person");
                ePerson.SetAttribute("id", person.Id.ToString());
                XmlElement eName = doc.CreateElement("Name");
                eName.InnerText = person.Name;
                XmlElement eAge = doc.CreateElement("Age");
                eAge.InnerText = person.Age.ToString();
                ePerson.AppendChild(eName);
                ePerson.AppendChild(eAge);
                ePersons.AppendChild(ePerson);
            }
            doc.Save("d:/data.xml");
            Console.WriteLine("创建成功");
            Console.ReadLine();
        }
    }

    class Person
    {
        public Person(int id, string name, int age)
        {
            this.Id = id;
            this.Name = name;
            this.Age = age;
        }

        public int Id { set; get; }
        public string Name { set; get; }
        public int Age { set; get; }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值