zoukankan      html  css  js  c++  java
  • c#正则表达式 特殊格式内容的提取

    我的命题是在类似格式“ToDo[123.125+a-b,2]”的格式中,提取123.125+a-b和2.前者为表达式,后者格式为纯数值。

    代码:

    string pattern = @"(?<=^round\[|^roundup\[|^rounddown\[)(?<number>.+)[,](?<digit>\d+)(?=\]$)";
    Match mt = Regex.Match(textBox3.Text, pattern, option);
    var a = mt.Groups["number"].Value;
    var b = mt.Groups["digit"].Value;

    当textBox3的text为“round[100.23,5]”时,最后a为100.23,b为5.

    当textBox3的text为“round[(round[100.23,5]),5]”时,最后a为(round[100.23,5]),b为5.

    当textBox3的text为“round[abcdefs]”时,也就是没有匹配值时,最后a为“”,b为“”.

    前面一个贪婪匹配,后一个只匹配数值,正是我想要的结果。

    作为保留,用时再温习。

    一起贴上微软官方的代码:

    string urlPattern = @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/";
    Console.WriteLine();
    Console.Write("Enter a URL for data parsing: ");
    string url = Console.ReadLine();
    Regex urlExpression = new Regex(urlPattern, RegexOptions.Compiled);
    Match urlMatch = urlExpression.Match(url);
    Console.WriteLine("The Protocol you entered was " +
    urlMatch.Groups["proto"].Value);
    Console.WriteLine("The Port Number you entered was " +
    urlMatch.Groups["port"].Value);

     运行上面的例程时,结果为:

    Enter a URL for data parsing: http://server.com:2100/home.aspx 
    The Protocol you entered was http 
    The Port Number you entered was :2100 

  • 相关阅读:
    梦断代码阅读笔记-01
    构建之法阅读笔记03
    寒假学习013-突如其来的被忘了的作业
    寒假学习012-安卓登陆注册
    寒假学习011-安卓连网
    寒假学习010-安卓联网初试
    寒假学习009-云服务器的使用
    构建之法阅读笔记02
    寒假学习007-activity1
    寒假学习006-activity
  • 原文地址:https://www.cnblogs.com/icyJ/p/regular_expression.html
Copyright © 2011-2022 走看看