C#正则表达式不匹配空字符串

时间:2012-06-20 16:24:12

标签: c# regex

我使用以下内容来匹配一行。一条线可能像下面那样。例如,如果field1存在但值为null,则它不匹配。即使field1或etc有空白或没有值,我希望它匹配。有任何想法吗?感谢

   field33
   field1 
   field2   lkjk
   field3   12.01.12

 static string partPattern = @"^(?<Key>\w+)\s+(?<Value>.*)$";

 line = line.Trim();  Match m = Regex.Match(line, partPattern);  
if(m.Groups["Key"].Length > 0) { 
 //do something heree 
}

所以当它查看field33时,line变为field33,即使key存在,正则表达式条件语句也会失败...

1 个答案:

答案 0 :(得分:1)

在正则表达式模式中,+表示One or More

尝试使用此字符串

@"^(?<Key>\w+)\s+(?<Value>.*)$

*表示Any Number包括0。

<强>更新

我测试了下面的代码,得到了这个输出。

        string t1 = "field1   ";
        string t2 = "field2   iopoi";
        string t3 = "field3   12.12.12";
        Regex rTest = new Regex(@"^(?<Key>\w+)\s+(?<Value>.*)$");
        if (rTest.IsMatch(t1))
        {
            MessageBox.Show("T1 match");
            foreach (Match m in rTest.Matches(t1))
                textBox1.Text += String.Format("Key: {0}\tValue: {1}\r\n", m.Groups["Key"].Value, m.Groups["Value"].Value);
        }
        textBox1.Text += "\n\n";
        if (rTest.IsMatch(t2))
        {
            MessageBox.Show("T2 match");
            foreach (Match m in rTest.Matches(t2))
                textBox1.Text += String.Format("Key: {0}\tValue: {1}\r\n", m.Groups["Key"].Value, m.Groups["Value"].Value);
        }
        textBox1.Text += "\n\n";
        if (rTest.IsMatch(t3))
        {
            MessageBox.Show("T3 match");
            foreach (Match m in rTest.Matches(t3))
                textBox1.Text += String.Format("Key: {0}\tValue: {1}\r\n", m.Groups["Key"].Value, m.Groups["Value"].Value);
        }

输出:

Key: field1 Value: 
Key: field2 Value: iopoi
Key: field3 Value: 12.12.12

我还测试了这个代码,在每个初始字符串上调用.Trim()

调用.Trim()

后,

t1 DID NOT MATCH

原因是因为.Trim删除了field1或field33之后的所有空格,以及正则表达式需要One or More空白字符。

新正则表达式:请尝试使用此代替@"^(?<Key>\w+)\s*(?<Value>.*)$"

注意,现在\ s后面跟着一个*。现在它也应该在使用Trim之后匹配。

相关问题