IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    A couple of regex recipes in C#

    Haidong Ji发表于 2015-10-21 03:05:57
    love 0

    For my own reference. Hope it’s helpful to you as well.

    Given this text pattern:
    Keyword blah blah keyword blah
    Line I don’t care.
    Keyword blah blah keyword blah
    I want everything after this line.
    Good stuff
    Good stuff

    Recipe 1: Returning all lines with keyword:

            //string pattern = @"keyword .+ keyword .+";
            public string GetKeywordLines(string pattern, string inputText)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Match m in Regex.Matches(inputText, pattern))
                {
                    sb.AppendLine(m.Groups[1].Value);
                }
                return sb.ToString();
            }
    

    Recipe 2: Returning all lines after “I want everything after this line.”

           //string pattern = @"^.+I want everything after this line\.(.+)$";
           public string SplitStatusUpdate(string pattern, string inputText)
            {
                Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                Match m = regex.Match(inputText);
                return m.Groups[1].Value;
            }
    

    ]



沪ICP备19023445号-2号
友情链接