日期:2014-05-19  浏览次数:20861 次

麻烦各位,求一个正则表达式!
假设我有一段文本
this.label1   =   new   System.Windows.Forms.Label();
this.label2   =   new   System.Windows.Forms.Label();
this.label3   =   new   System.Windows.Forms.Label();
我想把   label1   ,   label2   ,label3   也就是控件的name值取出来应该怎么写呢?

------解决方案--------------------
如果你的name都是放在this的后面倒是很好写
------解决方案--------------------
string sourceString = @ "this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
";
System.Text.RegularExpressions.MatchCollection results = Regex.Matches(sourceString,@ "this.([^=]*)[^;]* ",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
foreach(Match result in results)
{
WL(result.Groups[1].Value);
}

//////////////////////////////////////////////
MSN:bdbox@hotmail.com请给我一个与您交流的机会!
------解决方案--------------------
string input= "this.label1 = new System.Windows.Forms.Label();\nthis.label2 = new System.Windows.Forms.Label();\nthis.label3 = new System.Windows.Forms.Label(); ";//Console.ReadLine();
Regex r1=new Regex(@ "(? <=this\.)(? <name> \w+)(?=\s*=) ",RegexOptions.IgnoreCase|RegexOptions.Multiline|RegexOptions.Compiled);
foreach(Match m in r1.Matches(input)){
Console.WriteLine(m.Value);
}
------解决方案--------------------
终于能发了

string str = @ "this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label(); ";
Regex re = new Regex( "[^.]*\\.(? <name> [^ ]*)[^;]*; ", RegexOptions.None);
MatchCollection mc = re.Matches(str);
foreach (Match ma in mc)
{
MessageBox.Show(ma.Groups[ "name "].Value);
}