【问题标题】:Regular expressions : how to find [closed]正则表达式:如何找到[关闭]
【发布时间】:2013-06-17 14:17:33
【问题描述】:

为什么这个正则表达式不是这样构造的:

tmprect = string "gg_rct_MyReg1"
regex = @"^\s*set\s+"+tmprect+@"\s*=\s*Rect\s*\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s**(.+)\s*\).*$";

不适合

set gg_rct_MyReg1 = Rect (-704.0 ,   -352.0, 224.0   , 448.0) //rect 1

我做错了什么?

///已编辑:

string findrectcoord = @"^\s*set\s+" + tmprect + @"\s*=\s*Rect\s*\(\s*([^,\s]*)\s*,\s*([^,\s]*)\s*,\s*([^,\s]*)\s*,\s*([^)\s]*)\s*\).*$";
StreamReader file3 = new StreamReader(openFileDialog1.FileName);
string line2;
while ((line2 = file3.ReadLine()) != null)
{
    Regex foundrectr = new Regex(findrectcoord);
    Match foundrectm = foundrectr.Match(line2);
      if (foundrectm.Success)
       {
         MessageBox.Show("YES");

       }
  }

字符串:

set gg_rct_MyReg1 = Rect( -704.0  ,  -352.0, 224.0  , 288.0 ) //JassCode

找不到

【问题讨论】:

  • 这个问题写的不正确。 :-)
  • 你想用你的正则表达式做什么?您需要提供更多信息 - “这就是我想要发生的事情,这就是正在发生的事情”。简单更好。
  • 正则表达式不适用于这些数据。 string " set gg_rct_MyReg1 = Rect (-704.0, -352.0, 224.0, 448.0) //rect 1" 我需要找坐标。
  • tmprect 是否正确转义以包含在正则表达式中?见Regex.Escape
  • 你是否在构建正则表达式后分配tmprect

标签: c# regex


【解决方案1】:

正则表达式本身虽然丑陋且效率低下,但应该可以工作。不过,您确实需要在构建正则表达式之前将要添加到正则表达式中的字符串分配。在我们处理它的同时,让我们清理它:

string tmprect = "gg_rct_MyReg1";
Regex regexObj = new Regex(@"^\s*set\s+" + tmprect + 
                           @"\s*=\s*Rect\s*\(\s*([^,\s]*)\s*,\s*([^,\s]*)\s*,\s*([^,\s]*)\s*,\s*([^)\s]*)\s*\).*$");

([^,\s]*) 匹配除逗号或空格之外的任意数量的字符。这比.* 更具体,后者会匹配太多并迫使正则表达式引擎回溯。

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2015-04-27
    相关资源
    最近更新 更多