正则、序列化、XML

正则表达式

正则表达式是对字符串进行匹配的语法,像name like '%张%'一样,定义了一些特殊的“元字符”,用来判断一个字符串是否满足某个规则。正则表达式非常深,编译器都是基于正则表达式,掌握基本使用即可。
基本元字符
*.表示除了\n以外的任意的单个字符
[0-9]表示的是0到9之间任何一个整数数字;[a-z]任意一个小写字母,[A-Z]任意一个大写字母
\d数字,\D非数字,\s空白,\S非空白,\w小写字母和数字和汉字,\W特殊符号。正则表达式中的\是真的\。
\表示对于.等特殊字符转义
()提升优先级别和提取组
[]代表一个区间中的任意一个[abc\d]就代表abc或者数字中的任意一个字符
| 或者
+是出现1次到无限次
是出现0次到无限次
?是出现0次到1次
{5}出现5次,{1,2}一次或两次,{5,8}为5至8次,{1,}最少一次,{3,}最少3次
^以…开始,$以…结束

使用Regex.IsMatch(被匹配字符串, 正则表达式)判断是否匹配。C#中表示正则表达式最好前面加上@,可以避免转义带来的困扰。
常见正则表达式
1、这样写是有缺陷的Regex.IsMatch(“18911111234”, @"\d{11}")、Regex.IsMatch(“3333333333333333”, @"\d{11}"),应该使用^KaTeX parse error: Expected group after '^' at position 37: …1111234333", @"^̲\d{11}")
2、手机号:@"^11\d{10}KaTeX parse error: Expected group after '^' at position 7: " 3、@"^̲\d{5,10}“匹配QQ号
4、ipv4地址:@”^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}KaTeX parse error: Expected group after '^' at position 38: …68.1.15 5、@"^̲\w+([-+.]\w+)*@…" 匹配邮箱
6、[\u4e00-\u9fa5] 单个汉字 @"1{2,4}KaTeX parse error: Expected 'EOF', got '\d' at position 37: …15位、18位数字):@"^(\̲d̲{15})|^(\d{18})KaTeX parse error: Expected 'EOF', got '\d' at position 29: …最后一位可能是x) @"^(\̲d̲{17})[\dxX]"
9、日期格式:^\d{4}-\d{1,2}-\d{1,2}$


    案例
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    namespace TestConsole
    {
        delegate void MyDel();
        class Program
        {
    
            static void Main(string[] args)
            {
                Match match = Regex.Match("2015-01-10", @"^(\d{4})-(\d{1,2})-(\d{1,2})$");
                if (match.Success)
                {
                    string value1 = match.Groups[1].Value;//注意序号从1开始
                    string value2 = match.Groups[2].Value;
                    string value3 = match.Groups[3].Value;
                    Console.WriteLine(value1 + "-" + value2 + "-" + value3);
                }
                else
                {
                    Console.WriteLine("匹配不成功");
                }
                Console.ReadKey();
            }
        }
    }

对象序列化

简介
对象序列化是将对象转换为二进制数据(字节流),反序列化是将二进制数据还原为对象。对象是稍纵即逝的,不仅程序重启、操作系统重启会造成对象的消失,就是退出函数范围等都可能造成对象的消失,序列化/反序列化就是为了保持对象的持久化
BinaryFormatter类有两个方法:
void Serialize(Stream stream, object pbj)
对象obj序列化到Stream中
object Deserialize(Stream stream)
将对象从stream中反序列化,返回值为反序列化得到的对象
对象序列化的一些注意事项
要序列化的类型必须标记为:[Serializable]
该类型的父类也必须标记为: [Serializable]
该类型中的所有成员的类型也必须标记为: [Serializable]
序列化只会对类中的字段序列化,(只能序列化一些状态信息)
类结构修改后之前序列化的内容尽量不要用了,否则可能会出错;
为什么要序列化?
保持对象的持久化,将一个复杂的对象转换流,方便我们的存储与信息交换
应用:ASP.net中进程外Session要求对象可序列化;
还有Xml序列化,应用开发中Json序列化已经代替了二进制序列化和Xml序列化等
面试题:类可序列化的条件是?
答:这个类必须标记为Serializable,如果这个类有父类,那父类也必须要编辑为Serialzable类型的,如果这类所有成员的也必须要编辑为Serializable。
案例

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;//序列化需要引用的程序集
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace TestConsole
{
    delegate void MyDel();
    class Program
    {

        static void Main(string[] args)
        {
            Person p = new Person();
            p.Age = 12;
            p.Name = "蛋蛋";
            BinaryFormatter bf = new BinaryFormatter();
            //using (Stream stream = new FileStream(@"f:\1.data", FileMode.Create))
            //{
            //    bf.Serialize(stream, p);//序列化
            //}
            Console.WriteLine("对象二进制序列化成功!");
            using (Stream stream = new FileStream(@"f:\1.data", FileMode.Open))
            {
                Person dP = (Person)bf.Deserialize(stream);//方序列化(当类结构变了后就尽量不要在使用这个对象,避免带来不必要的麻烦)
                Console.WriteLine("Age=" + dP.Age + ",Name=" + dP.Name);
            }

            Console.ReadKey();
        }
    }
    [Serializable]
    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
        private DanDan DanDan { get; set; }//这个属性的类型也要标记为Serializable
    }
    [Serializable]
    class DanDan
    {
        public string Id { get; set; }
    }
}

Xml

简介(可扩展标记语言)
XML优点:容易读懂;格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写。
Xml就是用一种格式化的方式来存储数据,我们可以通过用记事本打开。
.net程序中的一些配置文件app.config、web.config文件都是xml文件。
XML语法规范:标签/节点(Tag/Node)、嵌套(Nest)、属性。标签要闭合,属性值要用""包围,标签可以互相嵌套
XML树,父节点、子节点、兄弟节点(siblings)
xml编写完成以后可以用浏览器来查看,如果写错了浏览器会提示。如果明明没错,浏览器还是提示错误,则可能是文件编码问题。
语法特点
严格区分大小写
有且只能有一个根节点
有开始标签必须有结束标签,除非自闭合:
属性必须使用双引号
(可选)文档声明:<?xml version="1.0" encoding="utf-8"?>
注释:
注意编码问题,文本文件实际编码要与文档声明中的编码一致。
读取xml文件

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace TestConsole
{
    delegate void MyDel();
    class Program
    {


        static void Main(string[] args)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(@"f:\1.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();
        }
    }
}

region xml文件

//
//
// < StuName > 张三 </ StuName >
// </ Student >
// < Student StuID=“22”>
// 李四
//
//
#endregion xml文件

创建xml文件

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace TestConsole
{
    delegate void MyDel();
    class Program
    {


        static void Main(string[] args)
        {
            Person[] persons = { new Person(1, "rupeng", 8), new Person(2, "baidu", 6) };
            XmlDocument doc = new XmlDocument();
            XmlElement ePersons = doc.CreateElement("Persons");
            doc.AppendChild(ePersons);//添加根节点
            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("f:/1.xml");
            Console.WriteLine("创建成功");
            Console.ReadKey();
        }
    }
    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; }
    }

}

  1. \u4e00-\u9fa5 ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值