c#正则表达式之间的区别.Match()。值和匹配()。ToString()

时间:2013-01-18 23:17:55

标签: c# regex

我有以下代码:

Match matcher = new Regex("[0-9]+.[0-9]+.[0-9]+").Match("12/02/1994");

if (matcher.Success)
{
   string matchedString1 = matcher.Value;
   string matchedString2 = matcher.ToString();
}

在这种情况下,matchedString1matchedString2包含相同的值"12/02/1994"matcher.Valuematcher.ToString()是否始终为任何正则表达式返回相同的结果?

2 个答案:

答案 0 :(得分:5)

Match类派生自Group类,该类派生自Capture类。

Capture类使用以下代码覆盖ToString()方法:

[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
    return this.Value;
}

所以,是的,它是相同的值。

答案 1 :(得分:2)

来自 MSDN ;

Capture.Value财产;

  

从输入字符串中获取捕获的子字符串。

Capture.ToString()方法。

  

通过调用,从输入字符串中检索捕获的子字符串   属性。

即使我们查看 .NET Reflector ,我们也可以看到Capture类覆盖ToString()这样的方法;

[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
    return this.Value;
}

所以,是的。它们具有相同的价值。