使用c#regex搜索文本

时间:2013-06-17 11:58:30

标签: c# regex

通过c#regex帮助查找所有“rect NAME = null”。 (在全局和全球之间)

    //Text example:
...
         globals
            ...
        boolexpr cj_true_bool_4896bnao87
        string udg_globals = "endglobals"
        trigger gg_trg___________________________u=null
        rect gg_rct_MyReg1=null
        rect     ra2462346  =            null
            ...
          endglobals
...

我的代码(,工作):

  1. private void openFileDialog1_FileOk(object sender,CancelEventArgs E)                 {                     string startglobs = @“^ \ s * globals \ s * $”;                     string endglobs = @“^ \ s * endglobals \ s * $”;                     string currrect = @“^ \ s * rect \ s +(。)\ s = \ s * null \ s *”;

                    using (StreamReader file = new StreamReader(openFileDialog1.FileName))
                    {
                        string currline;
                        bool globalstate = false;
                        while ((currline = file.ReadLine()) != null)
                        {
                            /* find globals */
                            Regex startr = new Regex(startglobs);
                            Match startm = startr.Match(currline);
                            if (startm.Success)
                                globalstate = true;
    
    
                            /* find endglobls */
                            Regex endr = new Regex(endglobs);
                            Match endm = endr.Match(currline);
                            if (endm.Success)
                                globalstate = false;
    
                            /* if opened globals find global rect */
                            if (globalstate)
                            {
                                Regex foundrectr = new Regex(currrect);
                                Match foundrectm = foundrectr.Match(currline);
                                if (foundrectm.Success)
                                {
                                    MessageBox.Show(foundrectm.Groups[1].ToString());
                                }
                            }
                        }
    
                    }
    
                }
    

1 个答案:

答案 0 :(得分:1)

我会给你一个提示......

你想要的正则表达式是

rect (.*)\s?=\s?null

您现在需要学习如何使用正则表达式运行它,并且您可能会发现MatchCollections和Groups很有趣。

现在已经足够让你在10分钟内解决问题,但你必须自己做一些阅读...