zoukankan      html  css  js  c++  java
  • 正则表达式

    核心理解

    1、通配符: d w s .
    2、重复次数: ? + * {}
    符合通配符要求的出现的个数
    3、进阶1: () |
    ()表示一个区域内
    4、进阶2: (?<year>d{2,4}) (?<key>.?)
    (?<key>.
    ?) 表示取符合后面通配符+重复次数(.?)的,命名为key
    (?<key>.+?)
    (?<>) 固定写法
    (?<key>.
    ?) .*会出现贪婪匹配,再加上?,则会取最少,符合要求
    比如:
    <message id="Ki9cV-494" to="15528235259@iz28axqtx19z" from="123456@iz28axqtx19z/Spark" type="chat" xmlns="jabber:client"> <body>233333</body> <thread>7JhcOr</thread> <x xmlns="jabber:x:event"> <offline /> <composing /> </x></message>
    正则表达式
    <message id="(?<id>.+?)" to="(?<to>.+?)@iz28axqtx19z" from="(?<from>.+?)@iz28axqtx19z/Spark" type="(?<type>.+?)" xmlns="(?<xmlns>.+?)"> <body>(?<body>.+?)</body> <thread>(?<thread>.+?)</thread> <x xmlns="(?<xmlns2>.+?)"> <offline /> <composing /> </x></message>
    .+? 保证不会往下面继续取,跨越id,to,from….取值
    5、多条件,或匹配
    (匹配1)|(匹配2)|….
    比如处理如下格式:1995年1月3日;1995.1.3;1月3日;1-3
    (d{4,4}年d{1,1}月d{1,1}日)|(d{4,4}.d{1,1}.d{1,1})|(d{1,1}月d{1,1}日)|(d{1,1}-d{1,1})
    进阶:((A|B))?((C|D|E))….
    即A、B两种匹配模式取或,C、D、E取或,AB、CDE再相互关联

    C#示例

    1、摘选示例文本
    去除 ,"等转义字符串
    2、将变化部分用正则表达式改写(运用正则表达式测试器)
    3、将需要提取的变化部分作命名提取
    4、使用提取出的部分(C#部分)

    string ToBeRegex = @"m=39536; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, u=130****7736; Domain=uspard.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, rn=%E6%9B%BE%E5%9B%BD%E5%AF%8C; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, lid=60637; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, wx=""""; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, bs=800301%2C800201; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, t=1508417567138; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/, s=4fd514113bde1ce8c10058148cd16d6a; Domain=baidu.com; Expires=Sat, 21-Oct-2017 12:52:47 GMT; Path=/";
    //.+?任意字符串
    //()表示一个集合,?<name>为值命名
    //IgnoreCase表示忽略大小写
    Regex regex = new Regex("m=(?<m>.+?);.+?u=(?<u>.+?);",RegexOptions.IgnoreCase);
    var matches = regex.Match(ToBeRegex);
    if (matches.Success)
    {
        string m = matches.Groups["m"].Value;
        string u = matches.Groups["u"].Value;
    }
    

    以上是一条消息的处理,如果是多条,采用方法Matches

    正则表达式的测试工具

    推荐regextester

  • 相关阅读:
    LightOJ 1313 Protect the Mines (Convex Hull && Minimum Circle)
    Hangzhou Invitation Day1
    hdu 2907 Diamond Dealer (Convex Hull)
    LightOJ 1239 Convex Fence (Convex Hull)
    POJ 2164 && LA 3218 Find the Border (Geometry, PSLG 平面直线图)
    hdu 1140 War on Weather (3DGeometry)
    uva 10347 Medians (Simple Geometry)
    String匹配函数
    动态读取外部文件
    转_读取外部数据
  • 原文地址:https://www.cnblogs.com/Lulus/p/7877981.html
Copyright © 2011-2022 走看看