在正则表达式模式中,+表示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()每个初始字符串的代码。
调用后 t1 DID NOT MATCH.Trim()
这样做的原因是因为 .Trim 删除了 field1 或 field33 或其他任何内容之后的所有空格,并且正则表达式需要One or More空格字符。
新正则表达式:尝试改用它@"^(?<Key>\w+)\s*(?<Value>.*)$"
请注意,现在 \s 后面也跟着一个 *。现在它也应该在使用 Trim 后匹配。